如何检查 C 中 scanf 的额外输入?
How do I check for extra inputs in scanf in C?
我正在使用 scanf()
获取 x 的值,我想检查是否输入了除单个整数以外的任何值;如果是,我想重新输入。
这是我目前拥有的:
#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);
}
目前,当我输入由 space 分隔的 2 个整数时,例如 23 43
,程序打印出 43,而不是再次要求输入。
如有任何帮助,我们将不胜感激。
谢谢。
你需要用其他方式做到这一点,因为 int 只允许单个数字 example:1000 你可以做 like: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;
}
考虑使用 strtol()
检查字符串中的所有字符是否都已转换为数字。使用 fgets
或任何其他行 reader 读取字符串并从中提取数字:
char buffer[4096];
fgets(buffer, sizeof(buffer), stdin);
char *endptr;
long result = strtol(buffer, &endptr, 10);
if(*endptr != '[=10=]') { /* There is more input! */ }
作为奖励,您可以读取非十进制数并检查输入的数字是否在可接受的范围内。
我正在使用 scanf()
获取 x 的值,我想检查是否输入了除单个整数以外的任何值;如果是,我想重新输入。
这是我目前拥有的:
#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);
}
目前,当我输入由 space 分隔的 2 个整数时,例如 23 43
,程序打印出 43,而不是再次要求输入。
如有任何帮助,我们将不胜感激。
谢谢。
你需要用其他方式做到这一点,因为 int 只允许单个数字 example:1000 你可以做 like: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;
}
考虑使用 strtol()
检查字符串中的所有字符是否都已转换为数字。使用 fgets
或任何其他行 reader 读取字符串并从中提取数字:
char buffer[4096];
fgets(buffer, sizeof(buffer), stdin);
char *endptr;
long result = strtol(buffer, &endptr, 10);
if(*endptr != '[=10=]') { /* There is more input! */ }
作为奖励,您可以读取非十进制数并检查输入的数字是否在可接受的范围内。