【问题标题】:How to read space-separated 0-9 digits in C?如何在 C 中读取空格分隔的 0-9 位?
【发布时间】:2016-09-01 09:01:30
【问题描述】:

我正在尝试编写一个程序,该程序在 C 中读取 空格分隔的正数,并向任何其他格式的输入提供错误消息。

例如,以下输入是正确的:

0 1 2 3 4 5 6 7 8 9
9 8 7 6 5 4 3 2 1 0
7 6 5 4 3
1 2 3
...

对于所有其他输入,程序应终止并打印错误消息。例如:

0 1,2 3 4-5 67 89
0123456789
0a2b3c4d5e6f7g8h9i
...

这是我的尝试:

...
int inputArr[999];
int length = 0;
char c = getchar();

while ( c != '\n' ) {
    if ( isdigit(c) ) {
        inputArr[length] = c - '0';
        length++;
    } else {
        printf ("Wrong Input Format!\n");
    }
    c = getchar();
    if ( c != ' ' ) {
        printf ("Wrong Input Format!\n");
    } else {
        continue;
    }
}
...

但即使输入正确,也会出现错误消息。

更新:

当我输入以下内容时:

0 1 2 3 4 5 6 7 8 9

我希望程序不会给我任何错误消息,但我会收到 10 条错误消息(删除exit(1); 行之后)。我假设它是 1 和(即 9 条消息)之后的每个字符的一条错误消息,以及结尾的 '\n' 字符的 1 条消息。

【问题讨论】:

  • 谢谢,但不完全是:标题的目的主要是为了在索引上列出,引起人们的注意。但是帖子的正文也应该是一个问题。它应该准确地说明您的预期,出了什么问题,以及您的特定问题尽可能缩小。不要只问“为什么这不起作用”,而是具体问“为什么 X 不做 Y by Z,当手册声称 X 应该做 Y(引用)时”等等。
  • 你的逻辑似乎很糟糕。你有所有这些ifs,但他们没有elses。所以你基本上没有机会在正确的时间发现错误。而且您的换行检测也不完整。而且您没有检测输入结束的机制。
  • 我添加了 else 语句,但我仍然不明白为什么当输入格式正确时会收到错误消息。

标签: c arrays io


【解决方案1】:

试试这个:

#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>

void e() { puts("Bad input."); exit(EXIT_FAILURE); }

int main(void)
{
    for (int c1 = 0, c2 = 0; c1 != EOF && c2 != EOF; )
    {
        c1 = getchar();
        if (c1 == EOF || c1 == '\n') continue;   // file or line ends in "x "
        if (!isdigit(c1)) e();

        c2 = getchar();
        if (c2 != EOF && c2 != '\n' && c2 != ' ') e();

        printf("Got input: '%c'.\n", c1);
    }
}

此版本允许在行尾使用尾随空格。如果您希望允许尾随空格(即"1 2" 可以,但"1 2 " 是错误的),请将第一个条件更改为:

if (c1 == EOF || c1 == '\n' || !isdigit(c1)) e();

【讨论】:

  • 非常感谢。我会玩弄它。我正在考虑使多个空格可接受的输入格式。
  • @user6005857:你可能想要scanf,而不是手动完成所有这些。
【解决方案2】:

标志可用于在读取数字时发出信号并防止连续数字。不会拒绝连续的空格。

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>

int main( void)
{
    int inputArr[999];
    int c = 0;
    int length = 0;
    int gotdigit = 0;

    while ( ( c = getchar ( )) != '\n' && c != EOF) {
        if ( isdigit ( c) && !gotdigit) {//found digit and no prior consecutive digit
            inputArr[length] = c - '0';
            length++;
            if ( length >= 999) {
                break;
            }
            gotdigit = 1;//set true to prevent consecutive digits
        } else {
            if ( c == ' ') {
                gotdigit = 0;//set false. found space so next digit is ok
            }
            else {//not a space or was consecutive digit
                printf ("Wrong Input Format!\n");
            }
        }
    }

    return 0;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-03
    • 2011-11-30
    相关资源
    最近更新 更多