当用户尝试使用特殊符号的命令行参数启动程序时,如何编写显示错误的代码?当用户仅输入 1 或 0 时,我的程序就可以工作,并且我知道如何保护我的程序不与其他数字一起运行,但我不知道如何处理特殊符号。 我所说的特殊符号是指例如“$ #”等。我尝试应用您的解决方案,但它仍然不起作用。问题是,当我使用“121”运行程序时,它工作正常,它显示错误“错误”,但是当使用“1#”运行程序时,它只是停止工作并且不显示“错误” C语言
int main(int argc, char *argv[])
{
FILE *in = argc > 1 ? fopen(argv[1], "r") : stdin;
double x;
if (in != NULL){
while (fscanf(in, "%lf", &x) == 1){
if(x != 1 && x != 0){
printf("ERORR");
return 1;
}
最佳答案
目前尚不清楚什么是“特殊标志”。我假设您引用了不正确的输入,这将阻止代码跳过错误的标记。考虑一个不同的循环来读取 token 并验证输入。假设每个 token 最多 20 个字符。
#include <stdio.h>
#include <stdboolh>
static bool scan_int(FILE *fp, int *res_p)
{
bool first = true ;
while ( 1 ) {
int r = sscanf(work, " %d", res_) ;
if ( r == 1 ) return true ;
if ( r == EOF ) return false ;
// print a message on first error
if ( first ) { printf("ERROR\n") ; first = false ; };
// try skipping a character ;
getchar() ;
}
int main(int argc, char *argv[])
{
FILE *in = argc > 1 ? fopen(argv[1], "r") : stdin;
if (in != NULL){
int x ;
while ( scan_int(in, &x) ) {
if ( x != 0 || x != 1)) {
printf("ERROR\n");
return 1;
} ;
...
}
}
}
从帖子中看来,如果输入值无效 (0, 1),代码应该忽略非数字(特殊符号),但退出(从 main 返回 1)。这个逻辑被保留。
关于c - 特殊符号和命令行参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58893334/