[英]Why doesn't fscanf scan the integer at the end of the line?
I'm trying to read in a file that contains multiple lines of the form: 我正在尝试读取包含以下形式的多行文件:
www.someurl.com,timestamp
I am using the following code: 我正在使用以下代码:
char url[256];
unsigned int timestamp;
// Read each line from the input file.
while(fscanf(inputfile, "%s,%d", url, ×tamp) == 2) {
printf("%s was visited at %d\n", url, timestamp);
}
However, fscanf
scans the entire line into the string, and does not scan the timestamp into the integer. 但是,
fscanf
将整行扫描到字符串中,而不将时间戳扫描到整数中。 I'm sure this is a very basic mistake, but I can't figure it out. 我确定这是一个非常基本的错误,但我无法弄清楚。 Could someone please explain why this is, and how I can go about fixing it?
有人可以解释为什么会这样吗,我该如何解决呢?
When processing %s
, fscanf
expects a whitespace terminated string, and it's greedy as well. 在处理
%s
, fscanf
需要一个以空格结尾的字符串,并且它也很贪心。 So the entire line is read into the url. 因此,将整行读入url。
You can specify the forbidden character set directly: 您可以直接指定禁止的字符集:
fscanf(inputfile, "%[^,],%d", url, ×tamp)
Here's a bit more data about fscanf
variants and the format string. 这是有关
fscanf
变体和格式字符串的更多数据。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.