如何读取文本文件并从C++的每一行中获取字符串?

问题描述:

所以;我试图创建一种hang子手游戏,我想从我从互联网上下载的.txt文件中获得大约4900个单词,每个单词放在不同的行中。我正在尝试读取文件,但程序每次都会出现错误(1),即没有找到文件。我尝试过使用绝对路径,并将文件放在工作目录中,并使用相对路径,但每次出现相同的错误。任何人都可以看看并告诉我这有什么问题吗? 我是C++的新手,我开始学习Java,现在我想尝试一些新的东西,所以我不确定代码的结构是否存在一些错误。 谢谢大家!如何读取文本文件并从C++的每一行中获取字符串?

#include "stdafx.h" 
#include <iostream> 
#include <stdio.h> 
#include <vector> 
#include <fstream> 
#include <string> 
#include <algorithm> 
using namespace std; 

vector<string> GetWords(){ 
    ifstream readLine; 
    string currentWord; 
    vector<string> wordList; 

    readLine.open("nounlist.txt"); 

    while (getline(readLine, currentWord)) { 
     wordList.push_back(currentWord); 
    } 


    if (!readLine) { 
     cerr << "Unable to open text file"; 
     exit(1); 
    } 
    return wordList; 
} 
+3

if语句将经常进行检查后的ReadLine是在年底,所以它会一直输出错误。如果这就是你的意思。否则,当我尝试此操作时,我不会收到任何错误,它会正确读取行。 –

+2

@Jack of Blades是对的,在while循环中移动'if(!readLine)...'''''''。 –

+1

是的,在读取所有数据后,如果文件正确打开,没有意义。最好在尝试打开它后立即执行此操作。 – Galik

您已阅读所有数据后检查了readLine。您可以使用下面的代码:

if (readLine.is_open()) { 
    while (getline(readLine, currentWord)) { 
     wordList.push_back(currentWord); 
    } 
    readLine.close(); 
} else { 
    cerr << "Unable to open text file"; 
    exit(1); 
} 

IS_OPEN功能是检查的readLine与任何文件关联。

使用此代码,

std::ifstream readLine("nounlist.txt", std::ifstream::in); 
if (readLine.good()) 
{ 
    while (getline(readLine, currentWord)) 
    { 
     wordList.push_back(currentWord); 
    } 
}