我昨天问了一个问题,但我什么也没做。我正在使用 visual studio 和 marmalade,我已经在学习 C++,但我需要在这里完成一些事情,所以我需要你们的帮助和耐心。
我收到了一些回复,比如
std::ifstream inp("restrict_words.txt");
std::istream_iterator<std::string> inp_it(inp), inp_eof;
std::vector<std::string> words(inp_it, inp_eof);
// words now has ever whitespace separated string
// from the input file as a vector entry
for (auto s : words)
std::cout << s << '\n';
和
std::ifstream ist("restrict_words.txt");
std::string word;
std::vector<std::string> readWords;
while(ist >> word)
readWords.push_back(word);
//test
for(unsigned i = 0; i != readWords.size(); ++i)
std::cout << readWords.at(i) << '\n';
这是一件很容易的事,我没能做到。
我的游戏文件夹中有 KingChatFilter.app 和聊天文件夹。在这个聊天文件夹中,我有这个包含 160 个不同行的 160 个单词的 txt。
我需要做的就是阅读此 txt 并将其放入数组后检查此字符串中的某些字符串是否与我想要的匹配,这样我就可以做其他事情了。
请有人让我明白这一点谢谢:)
最佳答案
我写了几个函数来满足您的要求:
#include <iostream>
#include <vector>
#include <algorithm>
#include <fstream>
using namespace std;
// Reads the file line by line and put all lines into words vector.
void read_to_vector(const char* file_name, vector<string> &words)
{
ifstream input(file_name);
string line;
while (getline(input, line))
{
words.push_back(line);
}
}
// Returns true if word is in words. False otherwise.
bool find_word(vector<string> &words, string word)
{
vector<string>::iterator it; // In c++11 you can change this to
// auto it;
// Using std::find from algorithm library.
it = find(words.begin(), words.end(), word);
return it != words.end(); // If the end of vector words was reached, then word was NOT found.
}
int main()
{
vector<string> words;
string target = "level";
read_to_vector("data.txt", words);
if (find_word(words, target))
cout << "Word " << target << " found" << endl;
else
cout << "Word " << target << " not found" << endl;
return 0;
}
关于c++ - 从 .txt 文件获取文本到 vector<string> 的最佳方式是什么? C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22688732/