2012-03-27 140 views
1

从一个* .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循环在一次运行中退出。数组是空的。我在网上看了起来,试了试其他像这里给出的代码在

code tutorial

#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测试版。

+2

你为什么不使用'int tmp; cin >> tmp'并将结果存储在'std :: vector'或'std :: list'中? – 2012-03-27 00:45:54

+2

'std :: vector '确实是你的朋友。 'int nArray [100000];'可能会非常浪费记忆。 – 2012-03-27 00:49:59

+0

我同意使用std :: vector而不是在堆栈上分配数组。这只是一个初稿,我只是试图从文件中读取部分权利。我也会尝试尼克拉斯B的建议。尽管为什么fstream和fstream.getline()不起作用,但仍然好奇。谢谢。 – 2012-03-27 01:07:55

回答

2

这不是做你觉得它在做什么:

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. 
} 
-1

这是一个代码不错位 http://www.java2s.com/Code/Cpp/File/readingatextfile.htm
如果这适用于您的文件,然后简单地添加你的任务

nArray [我++] =的atoi(线);在cout之后。


如果它仍然有效,那么请注释该cout ..可能会很好地将它留在那里注释掉,因为它可能会向您的老师显示您的过程。有些PROFS只是想看到成品,所以这是给你

+0

哦..确保在启动while循环之前将i设置为零。 – baash05 2012-03-27 01:51:31

+1

这段代码很糟糕。 [它错误地处理EOF。](http://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-considered-wrong) – Blastfurnace 2012-03-27 02:55:08

+0

@Blastfurnace现在完全看到它..把读在while()中,它会很好。 – baash05 2012-05-11 04:15:33

0

我看不出有什么太大错误的第二个版本。

然而,在第一个版本,你调用file.getline(str,7);其中线有时会包含一个7位数。直到读取分隔符(默认为'\n')或读取了6个字符为止,在这种情况下设置了failbit

因为您只在while循环中测试eof,所以它不会退出。

如果将上述行中的getline调用和char数组声明中的7更改为8,则应该起作用。

所有的说法,@尼克拉斯B的建议使用int tmp; file >> tmp;和存储在vector可能是最简单的解决方案。