C ++从文件读取到向量

C++ read from file into a vector

我正在开发一个程序,它应该从一个文件中读取并将该文件的内容存储在一个向量中。我必须读取 .txt 文件的内容,并在字符串到达​​ ' ' 之前将其推回向量中。如果它是 space,您将跳过文件的那部分并继续推回 space 之后的内容。有谁知道使用什么函数来读取文件并将内容放入向量或数组中?谢谢你的时间。

int main()
{
    Code mess;
    ifstream inFile;
    inFile.open("message1.txt");
    if (inFile.fail()) {
        cerr << "Could not find file" << endl;
    }
    vector<string> code;
    string S;
    while (inFile.good()) {
        code.push_back(S);
    }
    cout << mess.decode(code) << endl;
return 0; 
}

您应该将您的阅读代码更改为

while (inFile >> S) {
    code.push_back(S);
}

您当前的代码没有将任何内容读入您的 S 变量。


关于循环条件while (inFile.good())请看这个问答:
Why is iostream::eof inside a loop condition considered wrong?

使用 std::iostream::good() 或多或少有相同的问题。

基本上你也可以这样做:

std::ifstream fh("text.txt");
    std::vector<std::string> vs;
    std::string s;
    while(fh>>s){
             vs.push_back(s);
    }

    for(int i=0; i<vs.size(); i++){

            std::cout<<vs[i]<<std::endl;
    }