精确的多次扫描输入

时间:2013-04-13 00:27:14

标签: c input scanf

我想知道如何使用简单的命令(例如while,if和数组)在一行中基本输入5个数字(特定整数)。例如: 如果我输入由空格分隔的5个数字, 1 2 3 4 5 程序会打印 1 2 3 4 5 但是,如果我输入少于5或超过5, 1 2 3 4 程序会打印 输入无效。 到目前为止我已经

#include<stdio.h>
int main(int argc,char *argv[]){
    int array[5], numbers;
    numbers = 0;
    while (numbers < 5) {
        scanf("%d", &array[numbers]);
        numbers  = numbers + 1
    }
    printf("%d %d %d %d %d\n", array[0], array[1], array[2], array[3], array[4]);
    return 0;
}

如果我们将所有阵列单元分配给9999(程序未使用的数字),该怎么办?我们创建一个循环来检查每个数组是否已更改为新值,如果它仍为9999则无效。但这里的问题仍然存在,我们如何只抓住一行不同数量的输入并继续前进。例如输入2 3 输出2 3 9999 9999 9999 或输入2 3 4 输出2 3 4 9999 9999

3 个答案:

答案 0 :(得分:1)

如果要强制输入在一行上,请首先读取输入然后解析它:

char line[100];
fgets(line, 100, stdin);
char x[100];
int n = sscanf(line, "%d %d %d %d %d %s", array, array+1, array+2, array+3, array+4, x)
if (n != 5)
    printf("invalid input\n");
else
    printf("read 5 numbers\n");

添加x以检测是否读取了太多。

答案 1 :(得分:0)

修改

要输入5个号码,您可以使用

int a[5];
char x;

scanf("%d %d %d %d %d", &a[0], &a[1], &a[2], &a[3], &a[4]);
while(scanf("%*[^\n]%*c")) {
    scanf("%c", &x); // after 5 ints were loaded, get rid of rest of the elements untill new line symbol
}
printf("%d %d %d %d %d\n\n", a[0], a[1], a[2], a[3], a[4]);

它会忽略5个数字之后的所有内容(事实上,它会写入x,直到出现新的行符号),但在这种情况下无法轻松设置要读取的数字。

如果排队的int少于5 {/ p>},您只需注意它就无法使用。

答案 2 :(得分:0)

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

int intRead(int array[], int size){
    char buff[128];
    int status=!0;//status == 0, Something happened!

    printf("\ninput %d integer:", size);
    while(fgets(buff, sizeof(buff), stdin)){
        int count=0;
        char*p;

        for(p=buff;NULL!=(p=strtok(p, " \t\n"));p=NULL){
            char *ck;
            int i;
            i=(int)strtol(p, &ck, 0);
            if(*ck){
                fprintf(stderr, "invalid input:can't parse of int <<%s>>\n", p);
                status=0;
                continue;
            }
            if(count < size){
                array[count++]=i;
                continue;
            }
            count = size + 1;//more than
            break;
        }
        if(count < size)
            fprintf(stderr, "invalid input: less than %d\n", size);
        else if(count == size) return status;
        if(count > size)
            fprintf(stderr, "invalid input: more than %d\n", size);
        printf("\ninput %d integer:", size);
        status = !0;
    }
    return 0;
}

int main(int argc,char *argv[]){
    int array[5];

    intRead(array, 5);//or: while(!intRead(array, 5));
    printf("%d %d %d %d %d\n", array[0], array[1], array[2], array[3], array[4]);
    return 0;
}