what was the syntax to input strings with more than one word i.e with space in between through scanf() not gets()
6 Answers
Is it
scanf("%[^\t\n]",string);
4 Comments
'\t' or '\n' like "\t123 456", nothing is read into string.char name[50];
printf("Enter your full name: ");
scanf("%[^\n]",name);
The %[^\n] conversion asks scanf( ) to keep receiving characters into name[ ] until a \n is encountered. It's a character-set, and starting with ^ means accept anything but that.
See https://en.cppreference.com/w/c/io/fscanf for details on how scanf works.
Better to used fgets() than scanf() for reading a line of user input.
If code must use scanf() then
char buf[100];
// Read up to 99 char and then 1 \n
int count = scanf("%99[^\n]%*1[\n]", buf);
if (count == EOF) {
Handle_EndOfFile(); // or IO error
}
if (count == 0) { // Input began with \n, so read and toss it
scanf("%*c");
}
Now parse buf for individual words.
Comments
char field1[40];
char field2[40];
char field3[40];
char field4[40];
char field5[40];
char field6[40];
/*
* sscanf( workarea, format, field of pointers )
* Interpret [^ ] as a field ending in a blank
* Interpret [^' '] as a field ending in a blank
* Interpret [^ |\t] as a field ending in blank or tab char
* Interpret [^' '|\t] as a field ending in blank or tab char
* Interpret [^ |\t\n] as a field ending in blank, tabchar or end-of-line
*
*/
strcpy(workarea,"Bread milk eggs cheese tomatoes cookies \n");
i=sscanf(workarea," %[^' '|\t] %[^[' '|\t] %[^' '|\t] %[^' '|\t] %[^' '|\t] %[^' '|\t|\n] ",
field1,field2,field3,field4,field5,field6);
This scan results in field1 containing "Bread", field2 containing "milk",... field6 containing "cookies". Between the first to last words you may one or more blanks or tabs The ending following cookies may be one of the three of space, tab or newline which will be dropped and not be part of "cookies".
Comments
I don't think this is possible with scanf(). If you know the number of words you want to read, you can read it with
char str1[100], str2[100];
scanf("%s %s", str1, str2);
Note that this is a huge security loophole, since a user can easily enter a string that's longer than the allocated space.
If you don't know the number of words, you might have to rephrase your question. What do you need to read it for? Why don't you want to use gets(), why does it have to be scanf()?
4 Comments
gets is its own security loophole too, and one should use fgets instead.You could read an entire line from a file if you want with:
scanf("%[^\n]\n", line);
Now, you could use sscanf to get every word:
sscanf(line, "%s", word);
line += strlen(word) + 1;
"line" and "word" are char pointers.
Note how line is going towards to get to the next word.
1 Comment
scanf("%[^\n]\n", line); will not always read an entire line. It does not save anything into line is input is "\n" and the '\n' will remain in stdin. sscanf(line, "%s", word); will not save anything into word if line is only made up of white-space.