通过scanf()输入多个字符串
输入带有多个单词的字符串的语法是什么,即通过scanf()之间的空格而不是gets()
是吗
scanf("%[^\t\n]",string);
char name[50]; printf("Enter your full name: "); scanf("%[^\n]s",name);
这里[^\n
表示scanf( )
将继续接收字符到name[ ]
直到遇到\n
。
我认为这不可能与scanf()。 如果您知道要阅读的单词数,可以阅读
char str1[100], str2[100]; scanf("%s %s", str1, str2);
请注意,这是一个巨大的安全漏洞,因为用户可以轻松输入比分配空间更长的字符串。
如果您不知道单词的数量,则可能需要重新解释您的问题。 你需要阅读什么? 你为什么不想使用gets(),为什么它必须是scanf()?
最好使用fgets()
不是scanf()
来读取一行用户输入。
如果代码必须使用scanf()
然后
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"); }
现在解析单个单词的buf
。
如果需要,您可以从文件中读取整行:
scanf("%[^\n]\n", line);
现在,您可以使用sscanf获取每个单词:
sscanf(line, "%s", word); line += strlen(word) + 1;
“line”和“word”是char指针。
注意线是如何进入下一个单词的。
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);
该扫描导致field1包含“Bread”,field2包含“milk”,… field6包含“cookies”。 在第一个到最后一个单词之间,您可以有一个或多个空格或制表符结尾以下的Cookie可能是空格,制表符或换行符中的三个之一,它们将被删除而不属于“cookies”。