我想使用 fscanf
来处理描述矩阵的文件的每一行,每一行对应矩阵的一行。 先验,我不知道任何给定文件中的矩阵包含多少列或行。
可以处理未知数量的行,因为当循环到达文件末尾时很容易停止循环。例如:
while(!feof(file)){
if (fscanf(file, "%f", &f)==1) {
printf("%f\n",f);
}
}
但是我需要知道变量f
属于哪一行。
例如:
n_row = 0;
while(!feof(file)){
if (fscanf(file, "%f", &f)==1) {
printf("a value %f is in row %d\n",f,n_row);
[if you met a "\n"]{
//then increment the row counter
n_row++;
}
}
}
如何做到这一点?
A.
最佳答案
有两种方法可以做到这一点:
- 使用
fscanf
逐行读取您的输入,然后使用来自行缓冲区,或 - 尝试读取
float
后的一个字符,并检查该字符是否为\n
。
这是第二种方法的工作原理:
while(!feof(file)) {
char next;
int count = fscanf(file, "%f%c", &f, &next);
if (count > 0) {
// There may not be '\n' on the last line,
// in which case count would be equal 1.
if (count == 1 || next == '\n') {
//then increment the row counter
n_row++;
}
printf("a value %f is in row %d\n", f, n_row);
}
}
虽然第二种方法对应于您希望看到的解决方案,但第一种方法更可靠。
关于c - fscanf 是否区分空格(换行符和空格),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26594387/