从一个* .txt文件读取数字我有一个* .txt文件,每行有一个整数。所以文件看起来像使用fstream从C++的* .txt文件读取数字使用fstream
103123
324
4235345
23423
235346
2343455
234
2
2432
我想从一个文件行逐行读取这些值,所以我可以把它们放在一个数组中。下面是一些代码,我写了实现这一
#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int nArray[1000];
int i = 0;
int _tmain(int argc, _TCHAR* argv[])
{
ifstream file("C:\Users\Chinmay\Documents\Array.txt");
//fstream file("C:\Users\Chinmay\Documents\Array.txt", ios_base::out);
//fstream file();
//file.open("C:\Users\Chinmay\Documents\Array.txt", ios_base::out);
bool b = file.is_open();
//file.seekg (0, ios::beg);
int i = file.tellg();
while(!file.eof())
{
//string str;
//getline(file, str);
//nArray[i++] = atoi(str.c_str());
char str[7] = {};
file.getline(str,7);
nArray[i++] = atoi(str);
}
file.close();
return 0;
}
该文件打开为布尔“B”返回true。但while循环在一次运行中退出。数组是空的。我在网上看了起来,试了试其他像这里给出的代码在
#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int nArray[100000];
int i = 0;
int _tmain(int argc, _TCHAR* argv[])
{
ifstream in("C:\Users\Chinmay\Documents\Array.txt");
bool b = in.is_open();
if(!in) {
cout << "Cannot open input file.\n";
return 1;
}
char str[255];
while(in) {
in.getline(str, 255); // delim defaults to '\n'
if(in) cout << str << endl;
}
in.close();
return 0;
}
这将立即返回为好。文件打开但没有读取数据。该文件不是空的,并有数据。有人能解释我要去哪里吗?我正在使用Visual Studio 2011测试版。
你为什么不使用'int tmp; cin >> tmp'并将结果存储在'std :: vector'或'std :: list'中? – 2012-03-27 00:45:54
'std :: vector'确实是你的朋友。 'int nArray [100000];'可能会非常浪费记忆。 –
2012-03-27 00:49:59
我同意使用std :: vector而不是在堆栈上分配数组。这只是一个初稿,我只是试图从文件中读取部分权利。我也会尝试尼克拉斯B的建议。尽管为什么fstream和fstream.getline()不起作用,但仍然好奇。谢谢。 – 2012-03-27 01:07:55