C语言 从文件中读取双精度浮点数?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4175127/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 07:02:24  来源:igfitidea点击:

Reading double-precision floating point numbers from a file?

cstringfiledouble

提问by primehunter326

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. 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. Thanks!

我的问题很简单;我有填充双精度浮点数的文本文件,我需要读入并存储在矩阵中。我知道如何打开文件,但从那里我不确定如何解析数据并进行转换。数字由空格和换行符分隔,每个数字前面都有一个符号(“+”或“-”)。我不确定应该使用哪个函数(scanf、fgetc 等)来读入数据。我对编程并不陌生,尽管这是我第一次广泛使用 C。欢迎详细解释,因为我想更熟悉如何处理此类任务。谢谢!

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. Is this correct?

编辑:应该澄清该文件是由代码生成的,因此无需担心用户会弄乱它。另外从阅读文档来看,我似乎可以使用 fread 将文件的所有内容加载到一个字符串中,然后使用 atof 解析出每个双精度值。这样对吗?

回答by Marek Sapota

double d;
scanf("%lf", &d);

scanf will skip the white space chars and let you read all values in a simple loop. If you are reading from a file then fscanf should be your choice.

scanf 将跳过空白字符,让您在一个简单的循环中读取所有值。如果您正在读取文件,那么 fscanf 应该是您的选择。

scanf documentationand fscanf documentation

scanf 文档fscanf 文档

回答by user411313

You should use fgets ANDsscanf and their return values like,

您应该使用 fgets ANDsscanf 及其返回值,例如,

char line[100];
while( fgets( line,100,filepointer ) )
  if( 1==sscanf(line,"%lf",&adoublevariable) )
    printf("%f",adoublevariable);
  else
    puts("not a double variable");