c++ - 从 .txt 文件获取文本到 vector<string> 的最佳方式是什么? C++

标签 c++ visual-studio mobile

我昨天问了一个问题,但我什么也没做。我正在使用 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 并将其放入数组后检查此字符串中的某些字符串是否与我想要的匹配,这样我就可以做其他事情了。

请有人让我明白这一点谢谢:)

enter image description here

最佳答案

我写了几个函数来满足您的要求:

#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/

相关文章:

c++ - 为什么全局变量会给函数调用中的编译器优化带来麻烦?

c# - 当我调用从 dll 导入的方法时抛出 AccessViolationException

c - 编译器的差异。 C语言

java - 为 Windows Mobile 6.1 选项编写应用程序?

javascript - 移动到普通网站重定向

c++ - 自动生成的 move 构造函数,成员不可 move

c++ - Qt : c++: how to read a ".dat" file

android - Visual Studio Xamarin android 应用程序崩溃

vb.net - VS 2010 : How can I change the order of the Project Properties>Settings?

audio - 尝试制作可与附近其他手机通信的应用程序