2017-12-02 130 views
-1

所以;我試圖創建一種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

回答

2

您已閱讀所有數據後檢查了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與任何文件關聯。

0

使用此代碼,

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