Reputation: 8605
I am trying to read user input with multiple fields. But the number of fields is not specified. I want to read all the words till the carriage return. i tried this code but it isnt working:
char str[256];
while(1)
{
scanf("%s", str);
if(str[strlen(str)] == '\n')
break;
else
printf("Got %s\n", str);
}
Examples of user input:
1. store file1
I need to parse store and file1 and break out of the loop.
2. store file1 file2
I need to parse store, file1 and file2 and break out of the loop.
Wondering how to break out of the loop at the carriage return.
thanks.
Upvotes: 4
Views: 5569
Reputation: 10381
Use
char str[256]
scanf("%255[^\n]", str); /*edit*/
which will read to a newline or (Edit:) 255 characters, whichever comes first.
Upvotes: 3
Reputation: 73
char str[256]
scanf("%256[^\n]", str);
Be careful with that code. It will overflow the char array for long strings. You want %255 in the scanf to accommodate the null terminator.
Upvotes: 1
Reputation: 63688
Try this.
char str[256];
while(1)
{
scanf("%s", str);
printf("Got %s\n",str);
if(fgetc(stdin) == '\n')
break;
}
Upvotes: 1
Reputation: 2135
Currently, your char array str[256] is filled with nothing or junk, so when you do a look up, you won't find it.
Upvotes: 1
Reputation: 36082
You could read using fgets() then split the buffer using strtok() into tokens
that way you have full control of everything.
Upvotes: 1