[英]Reading double-precision floating point numbers from a file?
My problem is pretty simple; 我的问题很简单; I have text file filled with double precision floating point numbers which I need to read in and store in a matrix.
我的文本文件充满了双精度浮点数,我需要读入并存储在矩阵中。 I know how to open the file but from there I'm not sure how to parse out the data and convert it.
我知道如何打开文件,但是从那里我不确定如何解析数据并将其转换。 The numbers are separated by spaces and newlines and each is preceded by a sign (either '+' or '-').
这些数字用空格和换行符分隔,并且每个数字前面都有一个符号(“ +”或“-”)。 I'm not sure which function (scanf, fgetc, etc.) I should use to read in the data.
我不确定应该使用哪个函数(scanf,fgetc等)来读取数据。 I'm not new to programming though this is my first time working extensively with C. Detailed explanations are welcome as I'd like to get more familiar with how tasks like this are handled.
尽管这是我第一次广泛地使用C,但我对编程并不陌生。欢迎详细的解释,因为我想更加熟悉如何处理此类任务。 Thanks!
谢谢!
Edit: Should have clarified that the file is generated by code so no need to worry about users messing with it. 编辑:应该已经阐明该文件是由代码生成的,因此无需担心用户会对其进行混乱。 Also From reading the docs it seems like I could just use fread to load all of the contents of the file into a string and then use atof to parse out each double.
另外从阅读文档来看,似乎我可以使用fread将文件的所有内容加载到字符串中,然后使用atof解析出每个double。 Is this correct?
这个对吗?
double d;
scanf("%lf", &d);
scanf will skip the white space chars and let you read all values in a simple loop. scanf将跳过空格字符,并允许您在一个简单的循环中读取所有值。 If you are reading from a file then fscanf should be your choice.
如果您正在读取文件,则应该选择fscanf。
scanf documentation and fscanf documentation scanf文档和fscanf文档
You should use fgets AND sscanf and their return values like, 您应该使用fgets 和 sscanf及其返回值,例如,
char line[100];
while( fgets( line,100,filepointer ) )
if( 1==sscanf(line,"%lf",&adoublevariable) )
printf("%f",adoublevariable);
else
puts("not a double variable");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.