visual使用fstream从C++中的*.txt文件中读取数字
visual Having reading numbers from a *.txt file in C++ using fstream
我有一个*.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:UsersChinmayDocumentsArray.txt");
//fstream file("C:UsersChinmayDocumentsArray.txt", ios_base::out );
//fstream file();
//file.open("C:UsersChinmayDocumentsArray.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:UsersChinmayDocumentsArray.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:UsersChinmayDocumentsArray.txt");
使用正斜杠(即使在Windows上)并检查文件打开是否立即成功:
std::ifstream ifs("C:/Users/Chinmay/Documents/Array.txt");
if (!ifs)
{
// Failed to open file. Handle this here.
}
我看不出第二个版本有什么问题。
然而,在第一个版本中,您调用的是file.getline(str,7);
,其中的行有时包含一个7位数的数字。这将一直读取,直到达到分隔符(默认'n'
),或者直到读取了6个字符,在这种情况下设置了failbit
。
因为您只在while
循环中测试eof
,所以它不会退出。
如果您在getline
调用中将7更改为8,并在上面的行中更改char
数组声明,那么它应该可以工作。
话虽如此,@Niklas B建议使用int tmp; file >> tmp;
并存储在vector
中可能是最简单的解决方案。
这是一段不错的代码http://www.java2s.com/Code/Cpp/File/readingatextfile.htm
如果这对你的文件有效,那么只需添加你的任务
nArray[i++]=atoi(线);在cout之后。
如果它仍然有效。。然后评论一下cout。。把它放在那里评论一下可能会很好,因为它可能会向你的老师展示你的过程。有些专业人员只想看到成品,所以这取决于
- 如何将 txt 文件中的行分隔为组件C++
- 在CMakeLists.txt的安装功能中使用.cmake文件有什么用
- 一种在C++中读取TXT配置文件的简单方法
- 无法打开.txt文件
- 如何使用CLion在Mac上创建一个新的.txt文件
- 我可以读取静态对象中的文件.txt吗?C++
- C++-需要读取存储在文件(.txt)中的时间戳并正确检索
- 具有文件.txt的 C++ 中的设置
- 如何在 CMakeList 中包含 h/hpp 头文件.txt而不是 cpp 或其他 hpp 文件
- 使用函数读取文件.txt中的矩阵
- 任何人都知道如何解决尝试将从MySQL数据库返回的行打印到文本文件(.txt)中的C++
- 读取文件.txt C
- 为什么我的方法不从文件.txt中读取float类型
- 如何读取名称(仅文件.txt)作为参数传递的文件(在任何目录中)?C++
- 读取文件".txt"并将每行的数据分配给循环列表中的新节点C++
- 如何用C++将字符串文件Txt解析成数组
- 如何在c++中读取和编辑文件txt
- 从文件.txt读取字符串数组并使用它来玩康威的生命游戏
- 导入文件txt时出错
- 如何仅读取文件.txt中的数字