【问题标题】:How do I read the number of characters from a input in C?如何从 C 中的输入中读取字符数?
【发布时间】:2021-01-04 18:35:36
【问题描述】:

我正在尝试读取字符数,包括空格。 我使用 scanf 函数使用 %c 检查字符。另外,我将如何将输入存储到数组中?

#include <stdio.h>

int main(void) {
  char n, count= 0;

  while (scanf("%c", &n) != EOF) {
    count = count+1;
  }  

  printf("%d characters in your input \n", count);

  return 0;
}

当我测试输入(带空格)时,例如 abcdefg 它不打印任何东西。

【问题讨论】:

  • scanf 对于这项任务来说是不必要的繁重,n=getc(stdin) 就足够了。好吧,您可以通过将它们写入足够长的数组来存储它们。
  • @Fread,你如何结束你的输入,用换行、文件结束信号或什么?
  • 尝试在循环中添加printf("%d\n", n); 以获取更多信息。
  • 我用 Ctrl-D 结束输入。添加 printf("%c\n", n);打印每个字符(我将格式说明符更改为 c)当我输入苹果时,它打印苹果,每个字符在自己的行上
  • 您需要按两次Ctrl+d。一次表示您已完成输入(返回最后一个字符,然后 scanf() 阻止等待下一个字符),然后在下一个 Ctrl+d 按键时返回 EOF,因为在输入结束之前没有读取任何字符已生成。

标签: arrays c input char character


【解决方案1】:

定义一个 MAX_CHAR 并在循环中检查它可以保护您免受无效的内存写入。 请记住,如果要打印或使用 char 数组,则数组的最后一个字节应该留给 '\0'。

#include <stdio.h>
#define MAX_CHAR 100

int main(void) {

char n[MAX_CHAR]={0}, count= 0;

while((count!=MAX_CHAR-1)&&(scanf("%c",&n[count])==1))
{
    if((n[count]=='\n')){
        n[count]=0;
        break;
    }
    count++;
}

printf("%d characters in your input [%s]\n", count, n);

return 0;
}

【讨论】:

  • UV 使用检查的好答案。注意:while(scanf("%c",&amp;n[count])) 应该是 while(scanf("%c",&amp;n[count]) == 1) 以避免在 EOF 上循环。考虑在读取数据之前执行count==MAX_CHAR-1,否则输入字节会丢失。
  • 感谢您推荐 EOF 检查
【解决方案2】:

scanf 在到达文件末尾时确实返回 EOF。但是为了让您看到这种情况发生,您应该在调用程序时为您的程序提供一个文件输入,如下所示:

./a.out < input.txt

input.txt 中,您可以输入任何您想要的文字。但是如果你想在命令行中工作,你应该阅读直到找到\n

#include <stdio.h>

int main(void) {
  char n, count = 0;
  scanf("%c", &n);
  while (n != '\n') {
    count = count+1;
    scanf("%c", &n);
  }  

  printf("%d characters in your input \n", count);

  return 0;
}

如果要将输入存储在数组中,则必须知道输入的大小(或至少可能的最大大小)

#include <stdio.h>

int main(void) {
  char n, count = 0;
  char input[100]; //the max input size, in this case, is 100
  scanf("%c", &n);
  while (n != '\n') {
    scanf("%c", &n);
    input[count] = n; //using count as the index before incrementing
    count = count+1;
  }  

  printf("%d characters in your input \n", count);

  return 0;
}

此外,如果不知道输入的大小或最大大小,则必须动态更改 input 数组的大小。但我认为这对你来说有点先进。

【讨论】:

    【解决方案3】:

    您的printf 不会打印任何内容,因为运行时无法访问它。您的代码在while 循环中永远循环

      while (scanf("%c", &n) != EOF) {
        count = count+1;
      }
    

    因为在这种情况下scanf 不会返回EOF

    【讨论】:

    • 在文件结尾我希望scanf() 返回EOF。您确定“scanf 在这种情况下不会返回 EOF”吗?
    • 循环没问题。从 en.cppreference.com/w/c/io/fscanf 你可以读到 scanf() 返回“如果在分配第一个接收参数之前发生输入失败,则 EOF。”
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-02-01
    • 1970-01-01
    • 2021-06-19
    • 2014-12-03
    • 1970-01-01
    • 2021-02-20
    • 2019-09-17
    相关资源
    最近更新 更多