[英]How can I read a text file and get a string from every line in C++?
所以; 我正在嘗試創建一種子手游戲,我想從從互聯網上下載的.txt文件中獲取單詞,其中包含大約4900個單詞,每個單詞在不同的行中。 我正在嘗試讀取文件,但是程序每次都以error(1)退出,即找不到文件。 我嘗試使用絕對路徑,也將文件放置在工作目錄中並使用相對路徑,但是每次遇到相同錯誤時,我都會嘗試使用絕對路徑。 誰能看一下,告訴我這是怎么了? 我是C ++的新手,我開始學習Java,現在我想嘗試一些新的東西,所以我不確定代碼的結構是否有錯誤。 感謝大家!
#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;
}
讀取所有數據后,您已經檢查了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);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.