简体   繁体   English

从文本文件中读取行并将字符串放入向量中?

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

I am trying to read each line of a textfile which each line contains one word and put those words into a vector.我正在尝试读取文本文件的每一行,每行包含一个单词并将这些单词放入一个向量中。 How would i go about doing that?我该怎么做?

This is my new code: I think there is still something wrong with it.这是我的新代码:我认为它仍然有问题。

#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 did, indeed, list the simplest form. @FailedDev 确实列出了最简单的形式。 As an alternative, here is how I often code that loop:作为替代方案,以下是我经常编码该循环的方式:

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

The entire program might look like this:整个程序可能如下所示:

// 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";
    }
}

Simplest form:最简单的形式:

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

No need for crazy c thingies :)不需要疯狂的c东西:)

Edit:编辑:

#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;
}

Keyword using is illegal C++!使用关键字是非法的 C++! Never use it.永远不要使用它。 OK?好的? Good.好的。 Now compare what I wrote with what you wrote and try to find out the differences.现在比较我写的和你写的,并尝试找出不同之处。 If you still have questions come back.如果您还有问题,请回来。

Simplest version:最简单的版本:

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

I'm omitting the includes and other gunk.我省略了包括和其他垃圾。 My version is almost the same as FailedDev's but by using a 'for' loop I put the declaration of 'line' in the loop.我的版本与 FailedDev 的版本几乎相同,但是通过使用“for”循环,我将“line”的声明放入循环中。 This is not just a trick to reduce the line count.这不仅仅是减少行数的技巧。 Doing this reduces the scope of line -- it disappears after the for loop.这样做会减少行的范围——它在 for 循环后消失。 All variables should have the smallest scope possible, so therefore this is better.所有变量都应该具有尽可能小的作用域,因此这样更好。 For loops are awesome. For 循环很棒。

A short version for C++11 and above. C++11 及更高版本的简短版本。 The vector is constructed directly from the file contents:该向量直接从文件内容构建:

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

Note that this code will only work if the input file is in the format described by the OP, ie "each line contains one word".请注意,此代码仅在输入文件采用 OP 描述的格式时才有效,即“每行包含一个单词”。 Or if you set special locale via qfile.imbue(), as mheyman kindly pointed out.或者,如果您通过 qfile.imbue() 设置特殊语言环境,正如 mheyman 所指出的那样。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM