【发布时间】:2015-12-20 00:41:30
【问题描述】:
所以我正在尝试在文件中搜索一系列浮点数。每个块的结束序列是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 次(但应被视为可能出现任意次数,ofc 具有不同的值,但始终以 0.0 结尾)。
【问题讨论】:
-
首先,您应该将所有
#define放在所有#include下方的顶部外部主右侧 -
@JackWilliams 它实际上是一个 void 函数,它在另一个函数中调用,该函数是更大程序的一部分,所以不是。只是为了您的方便而对其进行了修改。
-
@JackWilliams:这是纯粹的风格选择,与程序的正确性无关。
-
这段代码是否完整?
long *n; n = NULL;在fscanf(in_file,"%[^0.0];",n);和puts(&n);之前没有分配内存给n?取消引用NULL指针?然后,假设NULL是数字零,打印一个长度为零的字符串? -
应该
0.00结束这个块吗?-0.0怎么样?还是只发短信0.0?