簡體   English   中英

從文本文件中讀取行並將字符串放入向量中?

[英]Reading line from text file and putting the strings into a vector?

我正在嘗試讀取文本文件的每一行,每行包含一個單詞並將這些單詞放入一個向量中。 我該怎么做?

這是我的新代碼:我認為它仍然有問題。

#include <iostream>
#include <fstream>
#include <string>
#include <vector>
using namespace std;

int main()
{
    std::string line;
    vector<string> DataArray;
    vector<string> QueryArray;
    ifstream myfile("OHenry.txt");
    ifstream qfile("queries.txt");

    if(!myfile) //Always test the file open.
    {
        cout<<"Error opening output file"<<endl;
        system("pause");
        return -1;
    }
    while (std::getline(qfile, line))
    {
        QueryArray.push_back(line);
    }
    if(!qfile) //Always test the file open.
    {
        cout<<"Error opening output file"<<endl;
        system("pause");
        return -1;
    }

    while (std::getline(qfile, line))
    {
        QueryArray.push_back(line);
    }

    cout<<QueryArray[0]<<endl;
    cout<<DataArray[0]<<endl;

}

@FailedDev 確實列出了最簡單的形式。 作為替代方案,以下是我經常編碼該循環的方式:

std::vector<std::string> myLines;
std::copy(std::istream_iterator<std::string>(myfile),
          std::istream_iterator<std::string>(),
          std::back_inserter(myLines));

整個程序可能如下所示:

// Avoid "using namespace std;" at all costs. Prefer typing out "std::"
// in front of each identifier, but "using std::NAME" isn't (very) dangerous.
#include <iostream>
using std::cout;
using std::cin;
#include <fstream>
using std::ifstream;
#include <string>
using std::string;
#include <vector>
using std::vector;
#include <iterator>
using std::istream_iterator;
#include <algorithm>
using std::copy;

int main()
{

    // Store the words from the two files into these two vectors
    vector<string> DataArray;
    vector<string> QueryArray;

    // Create two input streams, opening the named files in the process.
    // You only need to check for failure if you want to distinguish
    // between "no file" and "empty file". In this example, the two
    // situations are equivalent.
    ifstream myfile("OHenry.txt"); 
    ifstream qfile("queries.txt");

    // std::copy(InputIt first, InputIt last, OutputIt out) copies all
    //   of the data in the range [first, last) to the output iterator "out"
    // istream_iterator() is an input iterator that reads items from the
    //   named file stream
    // back_inserter() returns an interator that performs "push_back"
    //   on the named vector.
    copy(istream_iterator<string>(myfile),
         istream_iterator<string>(),
         back_inserter(DataArray));
    copy(istream_iterator<string>(qfile),
         istream_iterator<string>(),
         back_inserter(QueryArray));

    try {
        // use ".at()" and catch the resulting exception if there is any
        // chance that the index is bogus. Since we are reading external files,
        // there is every chance that the index is bogus.
        cout<<QueryArray.at(20)<<"\n";
        cout<<DataArray.at(12)<<"\n";
    } catch(...) {
        // deal with error here. Maybe:
        //   the input file doesn't exist
        //   the ifstream creation failed for some other reason
        //   the string reads didn't work
        cout << "Data Unavailable\n";
    }
}

最簡單的形式:

std::string line;
std::vector<std::string> myLines;
while (std::getline(myfile, line))
{
   myLines.push_back(line);
}

不需要瘋狂的c東西:)

編輯:

#include <iostream>
#include <fstream>
#include <string>
#include <vector>

int main()

{
    std::string line;
    std::vector<std::string> DataArray;
    std::vector<std::string> QueryArray;
    std::ifstream myfile("OHenry.txt");
    std::ifstream qfile("queries.txt");

    if(!myfile) //Always test the file open.
    {
        std::cout<<"Error opening output file"<< std::endl;
        system("pause");
        return -1;
    }
    while (std::getline(myfile, line))
    {
        DataArray.push_back(line);
    }

    if(!qfile) //Always test the file open.
    {
        std::cout<<"Error opening output file"<<std::endl;
        system("pause");
        return -1;
    }

    while (std::getline(qfile, line))
    {
        QueryArray.push_back(line);
    }

    std::cout<<QueryArray[20]<<std::endl;
    std::cout<<DataArray[12]<<std::endl;
    return 0;
}

使用關鍵字是非法的 C++! 永遠不要使用它。 好的? 好的。 現在比較我寫的和你寫的,並嘗試找出不同之處。 如果您還有問題,請回來。

最簡單的版本:

std::vector<std::string> lines;
for (std::string line; std::getline( ifs, line ); /**/ )
   lines.push_back( line );

我省略了包括和其他垃圾。 我的版本與 FailedDev 的版本幾乎相同,但是通過使用“for”循環,我將“line”的聲明放入循環中。 這不僅僅是減少行數的技巧。 這樣做會減少行的范圍——它在 for 循環后消失。 所有變量都應該具有盡可能小的作用域,因此這樣更好。 For 循環很棒。

C++11 及更高版本的簡短版本。 該向量直接從文件內容構建:

ifstream qfile("queries.txt");
vector<string> lines {
    istream_iterator<string>(qfile),
    istream_iterator<string>()
};

請注意,此代碼僅在輸入文件采用 OP 描述的格式時才有效,即“每行包含一個單詞”。 或者,如果您通過 qfile.imbue() 設置特殊語言環境,正如 mheyman 所指出的那樣。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM