0

By using argc and argv after the int main(), we can easily write code to iterate through strings and sub chars as we want. I am wondering if we can do the same thing by prompting user for input; and access each individual string from the user input?

string s = GetString();

char * a;

a = strtok (s, " ");

while (a != NULL) /*when all tokens are called, the final strtok resturns NULL, so that the loop can be terminated*/
{

    for (int i = 0; i < 1; i++)
    {
        printf ("%c", toupper (a[0]));
    }
    a = strtok (NULL, " "); /*returning pointer (NULL token n+1), n represents how many times the loop is called*/

1 Answer 1

1

If I get that correctly, you need to get a space-separated list of strings from the user and store all of them into an array where each element represents a single string. I think you may want to use a function like strtok (declared in string.h). Execute

man strtok

in the terminal for more information!

7
  • So by looking up the strtok function, I was able to get it to work. Feb 16, 2015 at 1:56
  • So by looking up the strtok function, I was able to get it to work. So, to my understanding, by declaring " " in strtok function (e.g. a=strtok(s," ");), I'm technically separating the input string into tokens using space that user enters (here of course are our first and last name). The more confusing part is the next part:(I want to make sure that I actually understands what I am using here :)) while (a != NULL) { for (int i = 0; i < 1; i++) { printf ("%c", toupper (a[0])); } a = strtok (NULL, " "); Feb 16, 2015 at 2:03
  • If I understand correctly, when I declare space as NULL, the first time the while loop executes, the pointer looks for the space and determines that the part before space is token0. At the same time, the pointer is at the position after the first space, so when the next round the while loop is executed, we are actually reading token1, which is the last name now. Feb 16, 2015 at 2:10
  • I think I now understand it. For each while loop execution, the next space is searched, and modified to NULL, so that the pointer will start from after the NULL in the next execution of the loop. a = strtok(NULL, " "); is used to modify the " " to NULL in the input string. However, one other thing is still bothering me. If my condition is a != NULL, why doesnt the loop terminate after the first round, since the first space is now modified to NULL? Feb 16, 2015 at 2:43
  • @YinzhouZhu I'm having a hard time understanding your questions in the comment. Please update your questions with your follow-ups and code samples (if necessary) and let me know! Thank you!
    – kzidane
    Feb 16, 2015 at 11:16

You must log in to answer this question.

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