读取一个充满数字的文件时得到零
Getting Zeros When Reading A File Full of Numbers
我正在尝试读取一个有几百行的文件。每一行看起来大致如下(请记住,这些不是实际数字。只是格式的一个示例。)R 111.111 222.2222 123456 11 50.111 51.111
我试着用fscanf读取这个文件,然后打印出一些值,但当我打印出这些值时,所有变量都为0。我已经检查了文件,没有一行的所有变量的值都为0。我在用C++写作。
#include <fstream>
#include <iostream>
#include <string>
using namespace std;
int main(int argc, char** argv)
{
FILE *myfile;
myfile = fopen("tmp.txt", "r");
string type;
float dx;
float dy;
float intensity;
int nsat;
float rmsy;
float rmsx;
if (myfile == NULL) exit(1);
else
{
while ( ! feof (myfile) )
{
fscanf(myfile,"%s %f %f %f %i %f %fn",&type, &dx, &dy, &intensity, &nsat, &rmsx, &rmsy);
printf("F %f %f %f %i %f %fn", dx, dy, intensity, nsat, rmsx, rmsy);
}
}
}
您可以使用std::ifstream
执行此操作
注意:这段代码并不假设输入文件的格式总是很好,并且在一个规则中没有丢失任何值
#include <fstream> //for ifstream
#include <string> //for strings
ifstream stream ( "tmp.txt", ios::in );
string type;
float dx;
float dy;
float intensity;
int nsat;
float rmsy;
float rmsx;
while ( stream >> type){
stream >> dx;
stream >> dy;
stream >> intensity;
stream >> rmsy;
stream >> rmsx;
cout << type << 't'
<< dx << 't'
<< dy << 't'
<< intensity <<'t'
<< rmsy << 't'
<< rmsx << endl;
}
和input.txt=
R 111.1111 222.2222 123456 11 50.111
T 111.1111 222.2222 123456 11 50.111
这会再次打印出来,注意这是更惯用的C++。
输出=
R 111.111 222.222 123456 11 50.111
T 111.111 222.222 123456 11 50.111
您的代码有多个问题,但是:
问题是格式字符串开头的%s
。CCD_ 3匹配完整的行,因此包含所有值。
如果您确信数字前面只有一个字符,那么也许您可以使用%c
。
还要注意,您传递了一个指向scanf
的std::string
指针。这是无效的,因为scanf
需要一个char
缓冲区来存储字符串(%s
),这根本不是一个好主意,因为您不知道所需的缓冲区长度。
这对我有效:
#include <fstream>
#include <iostream>
#include <string>
using namespace std;
int main(int argc, char** argv)
{
FILE *myfile;
myfile = fopen("tmp.txt", "r");
char type;
float dx;
float dy;
float intensity;
int nsat;
float rmsy;
float rmsx;
// The NULL-if should be here, but left out for shortness
while ( ! feof (myfile) )
{
fscanf(myfile,"%c %f %f %f %i %f %f",&type, &dx, &dy, &intensity, &nsat, &rmsx, &rmsy);
printf("F %f %f %f %i %f %fn", dx, dy, intensity, nsat, rmsx, rmsy);
}
}
相关文章:
- 如何在C++中确定文本文件中的元素是字符还是数字
- 使用fstream对txt文件中的数字进行循环
- 如何在 C++ 中将文件中的逗号分隔数字读取到数组中?
- 为什么当我输入较大的数字时,我的程序会到达文件末尾?
- 如何从也包含C++字母的文本文件中提取某些数字?
- 如何将 UTF-8 文本从文件转换为某个可以迭代的容器,并检查每个符号是否为C++字母数字?
- 从.txt文件中读取浮点型数字并在公式中使用它们
- 在 txt 文件中显示前两个数字的程序
- 尝试将数字写入二进制文件时引发异常
- 为什么我的程序在读取/写入文件时会删除最重要的数字?
- C++:从文件中读取字符串和整数,并获得最大数字
- 一个C++程序,用于在输入位数时输出具有特定位数的 .txt 文件中的所有数字
- 如何读取具有数字间隔的文本文件?C++
- 如何知道文本文件中的输入是否是 C++ 中的有效数字
- 如何删除文件中的数字,通过 c++ fstream 的
- 在c++中读取文件时,它如何自动将字符放入字符数组,将数字放入整数变量
- 如何从txt文件c++中提取括号之间的数字
- 在获取从文件到矢量的每一行之后,数字将被更改或销毁
- 如何将数字输出到文件中,所有数字都具有相同的精度
- 如何检索文件数字签名信息