从文件中读取整数数据
我刚刚开始使用C++,并且正在研究codeval问题,所以如果有人这样做,他们会认识到这个问题,因为它是列表中的第一个。我需要打开一个具有3列空格分隔的整数值的文件。这是我的,在fizbuz.txt下。我需要从文件中获取整数值并将其存储起来,以便以后在程序中的其他地方使用。从文件中读取整数数据
1 2 10
3 5 15
4 5 20
2 8 12
2 4 10
3 6 18
2 3 11
8 9 10
2 5 8
4 9 25
现在我可以打开文件了,我用getline()来读取文件就好了,使用我的下面的代码。但是,我不希望它们是字符串格式,我希望它们是整数。所以我环顾四周,每个人都基本上说相同的符号(文件>> int1 >> int2 ...)。我已经写了一些代码,就是我在几个例子中看到的,并不像他们告诉我的那样。
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
string filename = "fizbuz.txt";
string line;
int d1,d2,len;
int i =0;
int res1[10], res2[10], length[10];
ifstream read (filename.c_str());
if (read.is_open())
{
// while(read>>d1>>d2>>len);
// {
// res1[i] = d1;
// res2[i] = d2;
// length[i] = len;
// i++;
// }
while (!read.eof())
{
read>>d1>>d2>>len;
res1[i] = d1;
res2[i] = d2;
length[i] = len;
}
read.close();
}
else
{
cout << "unable to open file\n";
}
for (int j = 0; j < 10;j++)
{
cout<< res1[j] << " " << res2[j] << " " << length[j] << '\n';
}
}
这两个while循环都在底部的输出函数中执行相同的操作。 fizbuz.txt的最后一行将返回到res1,res2和length的第一个元素,并且所有3的其余元素都是psuedorandom值,可能来自任何使用该内存块的程序。下面
4 9 25
32767 32531 32767
-1407116911 4195256 -1405052128
32531 0 32531
0 0 1
0 1 0
-1405052128 807 -1404914400
32531 1 32531
-1405054976 1 -1404915256
32531 0 32531
第一个版本应该只是你需要删除;
在while
线工作。
while (read >> d1 >> d2 >> len);
^
啊,我没有意识到那里,或者它甚至是重要的。为什么编译器不会为类似的东西吐出一个错误? – NathanielJPerkins 2015-04-03 07:21:32
@Thallazar因为这不是编译错误。您有责任避免此类错别字。 – herohuyongtao 2015-04-03 07:22:28
EX输出试试这个
while (!read.eof())
{
read>>d1>>d2>>len;
res1[i] = d1;
res2[i] = d2;
length[i] = len;
i++;
}
是的,它适用于第二个函数,这是一个愚蠢的事情,忘记了我的但是,无论我在哪里,他们都推荐了第一个符号,而且我并没有忘记i ++,那么为什么这不起作用呢? – NathanielJPerkins 2015-04-03 07:16:33
你忘了'我++' – 2015-04-03 07:13:34
我在这种情况下做了什么? – NathanielJPerkins 2015-04-03 07:14:22
@Thallazar你应该可能得到[好书](http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list)。 – molbdnilo 2015-04-03 07:15:54