[英]c: scanf reading integers
This scanf statement will read in numbers from input like 10ss
as 10 - how do I rewrite it to ignore an int that's followed by other characters? 这个scanf语句将从输入中读取数字,例如
10ss
和10-我如何重写它以忽略后面跟有其他字符的int? If 10ss
is read, it should ignore it and stop the for loop. 如果读取了
10ss
,则应忽略它并停止for循环。
for (int i = 0; scanf("%d", &val)==1; i++)
You can try reading the next character and analyzing it. 您可以尝试阅读下一个字符并进行分析。 Something along the lines of
遵循以下原则
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
or, in an attempt to create something "fancier" 或者,试图创建一些“爱好者”
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
But in general you will probably run into limitations of scanf
rather quickly. 但是总的来说,您可能很快就会遇到
scanf
限制。 It is a better idea to read your input as a string and parse/analyze it afterwards. 最好将您的输入读取为字符串,然后解析/分析它。
how do I rewrite it to ignore an
int
that's followed by other characters?如何重写它以忽略后面跟有其他字符的
int
?
The robust approach is to read a line with fgets()
and then parse it. 健壮的方法是使用
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++)
Additional code needed to detect excessively long lines. 需要额外的代码来检测过长的行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.