[英]Scanf not accepting second char string
我有一个二进制搜索功能,可以在数组中搜索单词,但是在搜索数组之前,我需要知道要搜索的单词。 我已经编写了代码来询问用户输入,但是程序会打印出输入请求,但不接受用户的任何东西。 我当时以为这是一个缓冲区问题,因为我在程序中有一个初始scanf,它从外部文件加载所有字符串并将它们放置在数组中。 我尝试在初始scanf之后使用fflush,并尝试使用gets重写第二个,如先前线程中所指出。 也许我没有正确实现它。 这是我到目前为止的内容,对于第二个scanf为何不起作用的任何提示,我们深表感谢。
#include "set.h"
#include "sortAndSearch.h"
#include <stdio.h>
#include <ctype.h>
#include <string.h>
int main(){
char names[320][30];
char str[30];
int i, j;
char *key;
int numOfWords;
char userWord[30];
Set set1, set2, set3;
//scan each char string into array names
for(i=0; scanf("%s", str) != EOF; i++){
strcpy(names[i], str);
}
//set number of words in file
numOfWords = i;
//sort names array
//bubbleSort(names, numOfWords);
//print out names, sorted
//for(i=0; i<numOfWords; i++){
// printf("%s\n", names[i]);
//}
printf("What word would you like to search for? ");
scanf("%s", userWord);
//addName2Set(set1, userWord);
return 0;
}
您的第二个scanf
无效,因为您的第一个scanf
永不终止。 除非关闭输入流,否则scanf
不会返回EOF
这可能是控制台关闭了。
由于scanf
返回读取的字符数,因此您应该使循环条件scanf(%s, str) != 0
。 这将使循环在用户未输入任何内容的情况下立即结束。
循环中的初始scanf()
读取EOF之前的所有内容,因此“想搜索什么单词?”一无所有。 scanf()
读取。
解决此问题的一种方法是从文件中读取初始名称( fopen()
, fscanf()
, fclose()
,并且文件名可能是程序的参数,也可能是固定名称)。
您可以尝试的另一种方法是clearerr(stdin);
在'What scanf()
。 该( clearerr()
)取消设置了EOF位,并允许scanf()
再次尝试。 如果程序的输入是终端,则可能会起作用。 如果程序的输入来自文件,则无济于事。
int main(int argc, char **argv)
{
char names[320][30];
char str[30];
int i, j;
char *key;
int numOfWords;
char userWord[30];
Set set1, set2, set3;
FILE *fp;
if (argc != 2)
{
fprintf(stderr, "Usage: %s word-file\n", argv[0]);
exit(1);
}
if ((fp = fopen(argv[1], "r")) == 0)
{
fprintf(stderr, "Usage: %s word-file\n", argv[0]);
exit(1);
}
//scan each char string into array names
for (i = 0; i < 320 && fscanf(fp, "%29s", str) != EOF; i++)
{
strcpy(names[i], str);
}
fclose(fp);
//set number of words in file
numOfWords = i;
这坚持要求您使用./a.out example.dat
(而不是./a.out < example.dat
)。 然后,它会或多或少地发挥您的作用。 当然,用于读取文件的代码应该在传递了文件名,数组和数组大小的函数中。 循环中的320为溢出保护,应为枚举enum { MAX_WORDS = 320 };
在数组声明和循环中都使用了它。 29
是溢出保护; 很难对其进行参数化,但是它比数组的第二维小一。
乍一看,您的问题和代码似乎完全错位了……
scanf()
是错误的函数,您想要从文件中读取文件,您想要fscanf()
,或者如果文件格式被格式化为每个单词都在其fgets()
行上,则fgets()
可以工作(换行停止读取每个字符串)。 同样,如果输入只是一个字符串,然后是return(newline),则可以使用gets()
而不是scanf()
来读取用户输入。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.