【发布时间】:2020-02-19 03:47:16
【问题描述】:
我正在尝试获取用户以 #1、#2、#3 格式输入的 RGB 代码。我对输入进行错误检查以确保它与 ', ' 格式匹配,并且可以从字符串中提取数字。但是,之后我无法检查输入是否为数字。
例如:如果用户输入:255, 0, 0f 程序仍然运行。
任何帮助将不胜感激!
char input[100];
printf("Enter RGB code \n");
scanf(" %[^\n]s", input);
//function to error check ', ' format
int c1,c2,c3;
//formats the input into three ints.
sscanf(input, "%d, %d, %d\n", &c1,&c2,&c3);
我只需要检查这些是否实际上是整数
【问题讨论】:
-
" %[^\n]s"的末尾没有's',除非您输入格式"#1, #2, #3s"-- 删除它:)转换说明符 是%[...].此外,您无法正确使用任何用户输入函数或转换函数,除非您检查返回...使用fgets( input, sizeof input, stdin)而不是scanf(" %[^\n]s", input);——消除@ 987654329@ 陷阱。 (同时从"%d, %d, %d\n"中删除'\n') -
"我错误检查输入以确保它与 ', ' 格式匹配" --> 代码不会这样做,因为它不会检查
scanf()的返回值。
标签: c