编辑:因为我知道我需要提供更多信息来让你们清楚,所以我添加了 main 函数和 getchoice 以及程序运行的两个图像。我的问题是,输入词尾后,我想先看到菜单然后做出选择,而它却提示我输入而不显示菜单。
该函数是一个更大程序的一部分,但这就是出现问题的地方。 它读取输入的单词,将它们放入数组中,直到输入关键字****END。但是,当输入此关键字时,它不会立即进入指定的 if 子句(您将在代码中看到)。我是新手,这可能是非常明显的事情,但非常感谢任何帮助。
#include <string.h>
#define M 50
#define N 15
void getText(char a[M][N])
{
int i, j;
char temp[N];
for (i = 0; i < 50; i++) {
for (j = 0; j < 15; j++) {
if (i == 49 && j == 14) {
printf("Maximum length of text reached.\n");
}
scanf("%s\n", temp);
if (strcmp(temp, "****END") == 0) {
printf("You entered the endkey.\n");
return;
}
strcpy(a[i], temp);
}
}
}
int main(){
int input;
while(1){
input = getChoice();
if(input == 1){
getText(text);
}
else if(input == 2){
getDictionary();
}
else if(input == 3){
correctText();
}
else if(input == 4){
saveText();
}
else if(input == 5){
getStats();
}
else if(input == 6){
break;
}
}
return 0;
}
int getChoice(){
int temp;
printf("Choose function:\n1: Enter text\n2: Enter dictionary\n3: Correct text\n4: Save text\n5: Get text statistics\n6: Exit program\n");
scanf("%d", &temp);
return temp;
}
Entered the endword and now it waits for input instead of showing the menu.
I inputed 2 for the second program function, then it showed the menu and proceeded to function 2.
最佳答案
除了不必要的双重嵌套循环之外,这一行
scanf("%s\n", temp);
应该是
scanf("%s", temp);
通常,您不应尝试使用 scanf
来匹配尾随空格,并且格式说明符 %s
会自动过滤掉前导空格(但请注意 %c
没有)。
还有其他错误,并且所提供的代码最初不完整,但值得注意的是,必须限制 %s
的输入长度以防止缓冲区溢出。
关于c - 这里是新手。 C函数执行过程中出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56089899/