【问题标题】:Save whole input in integer array (read with getchar)将整个输入保存在整数数组中(使用 getchar 读取)
【发布时间】:2019-04-17 09:04:49
【问题描述】:

我只能使用 stdio.h 库。所以我想用 getchar 读取用户输入,直到第一个“/”,然后想将读取的输入保存在一个整数数组中。从 while 循环中检查输入,我发现只有最后一个字符串是安全的。

例如,我输入“test/hello”,我想在名为“safe”的整数数组中安全地“测试”,这样我也可以在 while 循环之外使用它。

我已经用“putchar(safe[count]);”检查了while循环中的输入。但唯一安全的输入是字母“t”。 (根据上面的例子)

    #include <stdio.h>

    int count;
    char i;
    int safe[50];

    int main() {
        while (1) {
            i = getchar();
            count = 0;
            if (i == '/')
                break;
            safe[count] = i;
        }
        // putchar(safe[count]);
     }

【问题讨论】:

  • 你不加count
  • 您还应该添加一张支票,以免到达count &gt;= 50。另外,为什么要将字符存储为整数?
  • 为什么在循环内将count 设置为零?它现在只需将safe[0] 设置为 i。你必须增加它:safe[count++]= i;
  • 除了在count达到50时突破,还应该在i等于EOF时突破。此外,safe[] 可以使用类型 char 而不是 int 以节省空间。

标签: c getchar


【解决方案1】:

请参阅 cmets 了解原因,但以下是正确的:

int main() {
    count= 0;
    while (count<49) {
        i = getchar();
        if (i == '/')
            break;
        safe[count++] = i;
    }
    safe[count]= '\0';
 }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-07
    • 2020-07-27
    • 1970-01-01
    • 2022-09-28
    相关资源
    最近更新 更多