简体   繁体   English

在C中的fscanf-如何确定逗号?

[英]fscanf in C - how to determine comma?

I am reading set of numbers from file by fscanf(), for each number I want to put it into array. 我正在通过fscanf()从文件中读取一组数字,对于每个要放入数组的数字。 Problem is that thoose numbers are separated by "," how to determine that fscanf should read several ciphers and when it find "," in file, it would save it as a whole number? 问题是,如果数字以“,”分隔,如何确定fscanf应该读取多个密码,并且在文件中找到“,”时会将其保存为整数? Thanks 谢谢

This could be a start: 这可能是一个开始:

#include <stdio.h>

int main() {
    int i = 0;

    FILE *fin = fopen("test.txt", "r");

    while (fscanf(fin, "%i,", &i) > 0)
        printf("%i\n", i);

    fclose(fin);

    return 0;
}

With this input file: 使用此输入文件:

1,2,3,4,5,6,
7,8,9,10,11,12,13,

...the output is this: ...输出是这样的:

1
2
3
4
5
6
7
8
9
10
11
12
13

What exactly do you want to do? 您到底想做什么?

I'd probably use something like: 我可能会使用类似:

while (fscanf(file, "%d%*[, \t\n]", &numbers[i++]))
    ;

The %d converts a number, and the "%*[, \\t\\n]" reads (but does not assign) any consecutive run of separators -- which I've defined as commas, spaces, tabs, newlines, though that's fairly trivial to change to whatever you see fit. %d转换一个数字,“%* [,\\ t \\ n]”读取(但不分配)任何连续的分隔符-我将它们定义为逗号,空格,制表符,换行符,尽管那是更改为您认为合适的任何东西都是微不足道的。

Jerry Coffin's answer is nice, though there are a couple of caveats to watch for: 杰瑞·科芬(Jerry Coffin)的回答很好,尽管有一些警告需要注意:

  1. fscanf returns a (negative) value at the end of the file, so the loop won't terminate properly. fscanf在文件末尾返回一个(负)值,因此循环不会正确终止。

  2. i is incremented even when nothing was read, so it will end up pointing one past the end of the data. 即使没有读取任何内容, i也会递增,因此最终将指向数据末尾。

  3. Also, fscanf skips all whitespace (including \\t and \\n if you leave a space between format parameters. 另外,如果在格式参数之间保留空格,则fscanf会跳过所有空格(包括\\t\\n

I'd go for something like this. 我会喜欢这样的东西。

int numbers[5000];
int i=0;
while (fscanf(file, "%d %*[,] ", &numbers[i])>0 && i<sizeof(numbers))
{
    i++;
}
printf("%d numbers were read.\n", i);

Or if you want to enforce there being a comma between the numbers you can replace the format string with "%d , " . 或者,如果要强制数字之间使用逗号,则可以将格式字符串替换为"%d , "

fscanf(file, "%d,%d,%d,%d", &n1, &n2, &n3, &n4); but won't work if there are spaces between numbers. 但如果数字之间有空格,则无法使用。 This answer shows how to do it (since there aren't library functions for this) 此答案说明了如何执行此操作(因为没有库函数)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM