簡體   English   中英

如何檢查 C 的 scanf 中的額外輸入?

[英]How do I check for extra inputs in scanf in C?

我正在使用scanf()獲取 x 的值,我想檢查是否輸入了除單個 integer 以外的任何內容; 如果是,我想重新輸入。

這是我目前所擁有的:

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

int main(int argc, char const *argv[])
{
    int x;
    char c;

    int input = scanf("%i%c", &x, &c);

    while (input != 2 || c != '\n')
    {
        input = scanf("%i%c", &x, &c);
    }

    printf("x = %i\n", x);
}

目前,當我輸入以空格分隔的 2 個整數時,例如23 43 ,程序會打印出 43,而不是再次要求輸入。

任何幫助,將不勝感激。

謝謝。

考慮使用strtol()檢查字符串中的所有字符是否都已轉換為數字。 使用fgets或任何其他行閱讀器讀取字符串並從中提取數字:

char buffer[4096];
fgets(buffer, sizeof(buffer), stdin);
char *endptr;
long result = strtol(buffer, &endptr, 10);
if(*endptr != '\0') { /* There is more input! */ }

作為獎勵,您可以讀取非十進制數字並檢查輸入的數字是否在可接受的范圍內。

您需要以其他方式執行此操作,因為 int 只允許單個數字示例:1000 您可以這樣做:1000 2000 但是還有另一種方式可以詢問用戶他要輸入的數字計數,然后為 scanf 循環計數的數字然后你可以做任何你想做的事情,這里有一個例子:

#include <stdio.h>

int main()
{
    int loopTime = 0;
    int temp = 0;
    int result = 0;

    printf("Enter the count of number you need to enter: ");//the number of times scanf going to loop
    scanf("%d", &loopTime);

    printf("Now enter the numbers you going to store but after every number you need to press enter\n");

    for (int i = 0; i < loopTime; i++)
    {
        scanf("%d", &temp);
        result += temp;
    }

    printf("The Result is: %i", result);
    return 0;
}

暫無
暫無

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

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