簡體   English   中英

為什么這段代碼沒有正確重新提示?

[英]Why this code is not re-prompting correctly?

我對 C 完全陌生。當輸入值不是數字時,我想重新提示,當它是數字時,它應該小於 1。當我給出任何類型的字符串時,它都能正常工作。 但是當我給出任何數字時,它會轉到下一行而不打印“數字:”。然后在下一行,如果輸入值小於 1,它會再次打印“數字:”。

int x;
printf("Number: ");
while (scanf("%d", &x) != 1 || x < 1 )
{

    printf("Number: ");

    scanf("%*s");
}

它給我的結果是這樣的

結果

明智的做法是使用fgets讀取該行,然后使用sscanf解析輸入。 這樣,你就可以得到線路,然后檢查sscanf成功! 簡單的例子:

int target_number; // The number you will have at the end of this.
while (1) { // Loop for rechecking number
    char line[16]; // See notes on how to read the whole line.
    fgets(line, sizeof(line), stdin);

    // We use 1 here because sscanf returns the number of format specifiers that are matched. Since you only need one number, we use 1.
    if (sscanf(line, "%d", &target_number) != 1) {
        fprintf(stderr, "Invalid Input! Please enter in a valid number.");
        continue;
    }
}

// Do whatever you will with target_number

筆記

您可以在此處查看如何閱讀整行。

此代碼不安全!

它不能防止緩沖區溢出攻擊等。 請參閱上這樣做的正確方法。 如果這只是為了學習,你不必擔心。

/*This is how it will work the way you want. 
If I understand  your goal correctly, of course? 
If your goal was different, 
please specify and I will try to solve it.*/



#include<stdio.h>

int main(void)
{
int x;
printf("Number: "); 
while (scanf("%d.%*d", &x)!=1 || x<0) 
{
if(x<0)
{
printf("Number: ");
continue;
}
else
printf("Number: ");
scanf("%*s");
}
printf("Hello world!");
return 0;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM