C代码做...循环问题

时间:2013-12-17 13:41:29

标签: c

我目前遇到的问题与我的C代码中的do ... while循环有关。问题是,当我输入一个不正确的值来存储在dataTest [51]中时,它会验证并说明问题(例如,数据包长度超过50,只有数字)。但是,当它再次提示我输入有效值时,我输入正确的值并按Enter键,但输入不被识别为我"输入"将数据转换为变量,它被识别为换行符,就好像那里没有值。

char dataTest[51];

do {

    int stp = 0;
    valid = 0;

    printf("\nPlease enter the packet data (maximum of 50 numbers): ");
    while(getchar()!='\n');

    scanf("%s", dataTest);

    length = strlen(dataTest);

    if(length <= 50) { 

        for(i=0;i<=length && stp!=1;i++) { 

            if ( (dataTest[i] >= 0 && dataTest[i] <= '9') 
              || (dataTest[i] == '0') ) {

                valid=1; //set the valid variable equal to 1

            } else {

                printf("\nData must contain only numbers, '%c' is not a number.
                       Please try again. \n", dataTest[i]);

               stp = 1;
               valid=0; //set the valid variable to equal 0

            }

        }

    } else {

        while(getchar()!='\n');
        printf("\nData should have no more than 50 numbers, you have entered
        %i",length);
        valid = 0;

}

} while(valid!=1);

非常感谢任何帮助!

2 个答案:

答案 0 :(得分:0)

如果我将变量stp初始化为0,该程序适用于您的情况。如果认为您可以完全消除它并使用valid代替。这不能解决超过50个字符的缓冲区溢出问题,但我认为这不是您问题范围的问题。

编辑:解决所有问题的代码(...除了溢出的字符数)

以下是Joachim Pileborg建议的fgets解决方案(通知dataTest[i] >= '0'并删除换行符):

int valid, length, i;
char dataTest[50+3]; // 3: '\n','\0' + one more to test 50 characters overflow

do {

valid = 1;

printf("\nPlease enter the packet data (maximum of 50 numbers): ");
fgets(dataTest, sizeof(dataTest), stdin);

length = strlen(dataTest);
--length;   //  remove last '\n'

if (length <= 50) {
    for(i=0;i<length && valid;i++) { 

        if ( (dataTest[i] >= '0' && dataTest[i] <= '9')) {

            valid=1; //set the valid variable equal to 1

        } else {

            printf("\nData must contain only numbers, '%c' is not a number.Please try again. \n", dataTest[i]);

           valid=0; //set the valid variable to equal 0

        }

    }
} else {
    printf("\nData should have no more than 50 numbers");
    valid = 0;
}

} while(valid!=1);

答案 1 :(得分:0)

我认为这句话虽然(getchar()!='\ n');让你感到困惑,你可以摆脱它。

for循环应该是

for(i=0;i<=length-1 && stp!=1;i++) { 
    if ( dataTest[i] >= '0' && dataTest[i] <= '9' ) {
        valid=1; 
    } else {
        printf("\nData must contain only numbers, '%c' is not a number.Please try again. \n", dataTest[i]);
        stp = 1;
        valid=0; 
    }
}