读取由换行符分隔的文本文件。 unix上的C ++

时间:2014-02-23 19:32:45

标签: c++ file unix file-io fstream

好的我已经在www上尝试过很多不同的建议,并且提出了所有的例子。这是一件非常简单的事情,对我来说不起作用令人沮丧!我已将需要读取的文件附加到数据结构中。在示例中,我只是将其打印到屏幕上。以下代码以前对我有用,但现在还没有。我曾经在视觉工作室和unix上尝试过,而且都没有运行它。我最终需要它在unix上运行。

任何人都可以告诉我为什么这不起作用,或建议更好的方式来阅读我的文件? 示例文件:

word
book
programming

这是我在文件中读取的功能。

#include "stdafx.h"
#include <fstream>
#include <iostream>
#include <string>
#include "words.txt"
using namespace std;

int _tmain(int argc, _TCHAR* argv[])
{
ifstream file;
string line;

file.open("words.txt");
if(file.is_open()){
    while(getline(file, line)){
        getline(file, line);
        cout << line <<endl;
    }
}
file.close();



return 0;
}

谢谢。

该文件但是会抛出有关分隔符的错误。例如在使用g ++运行的unix中:

wordlist2.txt: 498841:1: error: missing terminating ' character
  incumbent's
  ^
wordlist2.txt:498875:13 warning: missing terminating ' character [enabled by default] 
  at your wits' end
  ^

在视觉工作室:

  Error 2   error C4430: missing type specifier - int assumed. Note: C++ does                not support default-int    
  Error 14  error C2146: syntax error : missing ';' before identifier 'mouse'

1 个答案:

答案 0 :(得分:1)

while (!file.eof())

不是个好主意。写下以下内容:

while (getline(file, line)) {
    cout << line << endl;
}

你当然不想

#include "words.txt"

删除此行!!

相关问题