Romonov
Romonov

Reputation: 8605

scanf in a loop till carriage return

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

Answers (5)

jonsca
jonsca

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

elbekay
elbekay

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

Prince John Wesley
Prince John Wesley

Reputation: 63688

Try this.

char str[256];
while(1)
{
    scanf("%s", str);
    printf("Got %s\n",str);
    if(fgetc(stdin) == '\n')
        break;
}

Upvotes: 1

Matthew
Matthew

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

AndersK
AndersK

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

Related Questions