所以我试图在文件中搜索一系列 float 。每个 block 的结束序列是0.0
。
可以这么说,我希望能够选择数字并将它们视为单独的字符串。如您所见,始终能够选择 0.0
作为选择范围的终点非常方便,但到目前为止我还没有做到这一点。
任何帮助将不胜感激!
当前代码:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main(){
#define TRUE 1 //for convenience later on
#define FALSE 0
#define CHUNK 1024 /* read 1024 bytes at a time, will be used later*/
char buf[CHUNK];
long *n;
n=NULL;
FILE *in_file = fopen("Measurements.txt","r");
if(in_file == NULL){ //test for files not executing again.
printf("File could not be read/found...");
exit(1);
}
//searching for end of string-block
fscanf(in_file,"%[^0.0];",n);
puts(&n); // trying to see if the fscanf function actually selected the right numbers
if(in_file){
fclose(in_file);
}
Measurement.txt 文件中的代码块:
210.5 210.9 213.8 209.3 214.7 214.2 214.4 211.8
213.9 213.6 214.5 214.3 213.2 215.5 210.9 212.3
215.4 212.4 210.6 210.4 216.2 209.9 211.4 213.7
213.9 209.2 210.4 211.8 215.8 216.4 216.1 209.6
217.5 209.8 210.8 216.4 209.4 217.0 212.3 217.7
216.5 214.4 217.2 215.5 217.6 211.6 211.8 213.7
217.0 211.3 217.2 211.2 210.2 215.1 217.2 211.9
216.8 217.5 212.1 217.5 212.9 217.2 211.0 215.2
216.8 211.6 210.9 216.4 210.8 213.0 210.9 217.2
217.3 216.2 213.4 209.2 215.9 212.1 210.5 211.3
215.5 212.7 216.6 214.2 215.9 209.4 212.1 217.6
213.2 213.5 217.6 214.6 211.1 209.6 213.6 213.7
209.2 210.4 214.7 215.0 0.0
此模式重复 4 到 5 次(但应视为它可能出现任意次数,具有不同的值但始终以 0.0
结尾)。
最佳答案
这个:
fscanf(in_file,"%[^0.0];",n);
并没有按照您的想法行事。特别是,%[^0.0];
格式不会选择“0.0 以外的数字”。你应该保持简单:
double num;
while (fscanf(in_file, "%f", &num) == 1) {
if (num == 0.0) {
// we are at the end of a block
}
}
请注意,我还使用了 double
而不是 long
,因为您有浮点输入。
关于c - 在以相同模式结尾的文件中搜索整数 block ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34376901/