gpt4 book ai didi

c - Scanf 不接受第二个字符字符串

转载 作者:太空宇宙 更新时间:2023-11-04 06:40:05 24 4
gpt4 key购买 nike

我有一个二进制搜索功能,可以在数组中搜索单词,但在搜索数组之前,我需要知道要搜索的单词。我已经编写了要求用户输入的代码,但程序打印出输入请求但不接受用户的任何内容。我认为这是一个缓冲区问题,因为我在程序中有一个初始 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。这将使循环在用户未输入任何内容而按下回车键时立即结束。

关于c - Scanf 不接受第二个字符字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9865713/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com