我有一个包含整数的 *.txt 文件,每行一个。所以文件看起来像
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;
}
随着 bool '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 测试版。
最佳答案
这不是你认为它在做的事:
ifstream file("C:\Users\Chinmay\Documents\Array.txt");
使用正斜杠(即使在 Windows 上)并立即检查文件打开是否成功:
std::ifstream ifs("C:/Users/Chinmay/Documents/Array.txt");
if (!ifs)
{
// Failed to open file. Handle this here.
}
关于c++ - 使用 fstream 从 C++ 中的 *.txt 文件中读取数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9881881/