0

I'm stuck. There's a way to assign argv[1] to a string variable?, like:

string keyword = argv[1];
2
  • Are you asking? If so, then yes, that should work, provided you include the appropriate library (e.g., cs50.h).
    – L.B.
    Aug 5 '15 at 20:38
  • Sorry, I've forgot the interrogation sign, but just fixed it. Aug 11 '15 at 1:28
1

The best and most efficient way is to out grow CS50.h use char* newString = argv[1]; argv will always be there so you might as well point to it or use it.

1
  • I have added this in my code but I still receive an error when check50 checks are done. The checks seem to expect that the first line of code will weed out words with letters and numbers in them, resulting in 'result 1;'. 'Hax0r2' was the example which is supposed to fail the initial keyword check. I gather this person was having the same issue.
    – Android1
    Mar 18 '17 at 9:34
1

string keyword = argv[1]; will work because you are assigning the address of string argv[1] to keyword. You can now treat keyword as a char array and access the individual characters as keyword[i].

You could also do this:

char keyword[strlen(argv[1])+1];
strcpy(keyword, argv[1]);

Instead of keyword pointing at the same memory location as argv[1], this would create a separate memory location and copy the string from argv[1] to keyword.

[EDIT: after seeing this again, I realized that the code also needed to have space for the end of string marker, so I added +1 to the declaration.]

If this answers your question, please accept this answer to remove the question from the unanswered question pool. Let's keep up on forum housekeeping. ;-)

2
  • in the example char keyword[strlen(argv[1])]; strcpy(keyword, argv[1]); the keyword array is declared memory before start of function/program call but the strlen() get the data during run time, i don't understand how this work can you explain me this Dec 15 '18 at 12:05
  • I think you may not understand the order of the function calls here. In the declaration of keyword, the code will calculate the value inside the square brackets first, by calling strlen() and then adding 1 to it. Once that value is determined, only then will keyword be created and memory allocated for it.
    – Cliff B
    Dec 15 '18 at 12:58
0

I just have made an ugly mistake trying to use toupper() with a string, and then thought that the problem was in the assignment of argv[1] to 'string keyword'. Sorry for the vain question.

1
  • All or at least most questions have merit. This the point in the course where learning about strings and argument vectors is very important.
    – ebobtron
    Aug 11 '15 at 21:40

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .