[英]c: scanf reading integers
这个scanf语句将从输入中读取数字,例如10ss
和10-我如何重写它以忽略后面跟有其他字符的int? 如果读取了10ss
,则应忽略它并停止for循环。
for (int i = 0; scanf("%d", &val)==1; i++)
您可以尝试阅读下一个字符并进行分析。 遵循以下原则
int n;
char c;
for (int i = 0;
(n = scanf("%d%c", &val, &c)) == 1 || (n == 2 && isspace(c));
i++)
...
// Include into the test whatever characters you see as acceptable after a number
或者,试图创建一些“爱好者”
for (int i = 0;
scanf("%d%1[^ \n\t]", &val, (char[2]) { 0 }) == 1;
i++)
...
// Include into the `[^...]` set whatever characters you see as acceptable after a number
但是总的来说,您可能很快就会遇到scanf
限制。 最好将您的输入读取为字符串,然后解析/分析它。
如何重写它以忽略后面跟有其他字符的
int
?
健壮的方法是使用fgets()
读取一行 ,然后对其进行解析。
// Returns
// 1 on success
// 0 on a line that fails
// EOF when end-of-file or input error occurs.
int read_int(int *val) {
char buf[80];
if (fgets(buf, sizeof buf, stdin) == NULL) {
return EOF;
}
// Use sscanf or strtol to parse.
// sscanf is simpler, yet strtol has well defined overflow funcitonaitly
char sentinel; // Place to store trailing junk
return sscanf(buf, "%d %c", val, &sentinel) == 1;
}
for (int i = 0; read_int(&val) == 1; i++)
需要额外的代码来检测过长的行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.