【问题标题】:How to read characters from stdin into an array in c?如何将stdin中的字符读入c中的数组?
【发布时间】:2019-09-20 03:15:21
【问题描述】:

我上一次做 C 是在 1991 年,现在我正在帮朋友做作业。

他必须从标准输入中获取字符到一个数组中。看起来很简单。我想我会使用this question as a reference point

我们有这个:

    printf("Input the line\n");
    i=read(0, arg, sizeof(char)*9);

IIUC 可以为我们获取字符,并且根据答案注释,我们应该能够将字符直接放入 arg 数组中,如下所示:

   while ((c = getchar()) != '\n' && c != EOF  && i2<9 ) {
     arg[i2] = c;
     i2++;
   }

但是会打印出这个(repl.it link):

 ./main
Input the line
123 456 789

893 456

所以看起来即使我试图通过在 while 循环中添加 i2&lt;9 来将其限制为索引 [0,8],它仍然会抓取 89 并将其放在数组的开头,因为数组只能容纳 9 个字符。

这是为什么?我是否以正确的方式解决这个问题?

我们不允许使用 fpurge。我假设教授正在尝试教他们如何手动执行此操作...

【问题讨论】:

    标签: c gcc stdin fflush


    【解决方案1】:

    我不明白你在这里要做什么,

       while ((c = getchar()) != '\n' && c != EOF  && i2<9 ) {
         arg[i2] = c;
         i2++;
       }
    

    上述循环主要用于消耗输入流中read之后的剩余输入。


    也就是说,与

    i=read(0, arg, sizeof(char)*9);
    

    您正在将9 字符读入arg,但您输入了11 字符和\n

    因此arg会有内容,

      123 456 (null)   <---contents
      01234567 8       <---indexes
    

    请记住 89\n 仍留在流中。因此,使用while 循环,您可以从索引089 读入arg 数组。

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-16
    • 1970-01-01
    • 2016-11-30
    • 2018-07-04
    相关资源
    最近更新 更多