art*_*rax -1 c scanf char getchar
我试图将多个单词输入和多行输入到一个数组中.但某些地方代码跳过获取输入并跳过结束程序.我已经尝试在'%s'(或'%s')之前和之后添加空格但是它不起作用(也许是因为它在循环中?).非常感谢任何人的帮助!如果我输入两三个以上的单词,它也会开始变得怪异:(我的目标是找到特定字母在所有这些单词和行中出现的次数.
#include <stdio.h> //include standard library
int main(){
int lineCount, occuranceCount;
printf("How many lines are you going to enter?");
scanf("%d", &lineCount);
char input[lineCount][100], searchChar;
for(int i=0; i<lineCount; i++){
printf("Please enter line #%d (100 characters of less):",i+1);
scanf("%s", &input[i]);
}
printf("What letter do you want to check the frequence in those lines? ");
scanf("%c", &searchChar);
for(int j=0; j<lineCount; j++){
for(int k=0; k<100; k++){
if(input[j][k] != '\0'){
if(input[j][k]==searchChar)
occuranceCount++;
}
}
}
printf("The letter occurs for %d time", occuranceCount);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
scanf(" %c", &searchChar);
^
Run Code Online (Sandbox Code Playgroud)
你需要这里的空间来消费任何\n来自stdin.
此外scanf()会读一个字不是一条线(空格分隔的单词)如你所想.
而且最好还是strlen(input[j])知道你应该阅读多少.
另一件事,使用size_t而不是int循环.
初始化occuranceCount为0.
还要避免在代码中buffer overrun使用漏洞scanf("%99s", input[i]);.
为了阅读你可以使用的一行fgets().