visual使用fstream从C++中的*.txt文件中读取数字

visual Having reading numbers from a *.txt file in C++ using fstream

本文关键字:文件 txt 读取 数字 中的 使用 fstream C++ visual      更新时间:2023-10-16

我有一个*.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。。把它放在那里评论一下可能会很好,因为它可能会向你的老师展示你的过程。有些专业人员只想看到成品,所以这取决于