Scanf cycle until carriage returns

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 until the carriage returns. I tried this code but it does not work:

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

User input examples:
1. save file1
I need to parse the repository and file1 and exit the loop.
2. Save file1 file2
I need to parse store, file1 and file2 and exit the loop.

It's amazing how to get out of the loop when the carriage returns.

thanks.

+4
source share
5 answers

Using

 char str[256] scanf("%255[^\n]", str); /*edit*/ 

which will be read in a new line or (Edit :) 255 characters, whichever comes first.

+3
source

You can read with fgets () and then split the buffer using strtok () into tokens

that way you have complete control over everything.

+1
source

Currently, the char str [256] array is not populated with anything or unwanted, so when you look, you won't find it.

+1
source

Try it.

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

Be careful with this code. It will overflow the char array for long strings. You want% 255 in scanf to host the null terminator.

+1
source

Source: https://habr.com/ru/post/1346858/


All Articles