繁体   English   中英

如何读取C中以空格分隔的0-9位数?

[英]How to read space-separated 0-9 digits in C?

我正在尝试创建一个程序,在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'字符的消息。

尝试这个:

#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();

可以使用标志来指示何时读取数字并防止连续数字。 连续的空间不会被拒绝。

#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;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM