This question already has an answer here:
How to read / parse input in C? The FAQ
                                
                                    (1个答案)
                                
                        
                                2年前关闭。
            
                    
我正在尝试将多个单词输入和多行输入到一个数组中。但是在某些地方,代码跳过了获取输入的过程,并跳过了结束程序的过程。我尝试在'%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;
}

最佳答案

  scanf(" %c", &searchChar);
         ^


您需要这里的空间才能使用\n中的任何stdin

另外,scanf()会按照您的想法读取一个单词,而不是一行(空格分隔的单词)。

而且最好使用strlen(input[j])来了解您应该阅读多少。

另一件事,在循环中使用size_t而不是int

occuranceCount初始化为0

另外,为避免buffer overrun漏洞,请在代码中使用scanf("%99s", input[i]);

为了读取一行,您可以使用fgets()

关于c - 为什么scanf跳过获取字符串输入的步骤? ,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/47278102/

10-11 21:59
查看更多