Leer la línea del archivo de texto y poner las cadenas en un vector?


Estoy tratando de leer cada línea de un archivo de texto que cada línea contiene una palabra y poner esas palabras en un vector. ¿Cómo haría eso?

Este es mi nuevo código: creo que todavía hay algo mal en él.

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

}
 21
Author: Luksprog, 2011-12-03

3 answers

@FailedDev hizo, de hecho, una lista de la forma más simple. Como alternativa, así es como a menudo codifico ese bucle:

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

Todo el programa podría verse así:

// 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";
    }
}
 30
Author: Robᵩ,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-12-03 03:57:04

Forma más simple:

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

No hay necesidad de cosas locas c:)

Editar:

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

Uso de palabras clave es ilegal C++! Nunca lo uses. OK? Bien. Ahora compara lo que escribí con lo que escribiste y trata de descubrir las diferencias. Si aún tienes preguntas, vuelve.

 29
Author: FailedDev,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-02-18 21:26:32

Versión más simple:

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

Estoy omitiendo los includes y otra mugre. Mi versión es casi la misma que la de FailedDev, pero usando un bucle 'for' puse la declaración de 'line' en el bucle. Esto no es solo un truco para reducir el número de líneas. Hacer esto reduce el alcance de la línea disappears desaparece después del bucle for. Todas las variables deben tener el menor alcance posible, por lo que esto es mejor. Los bucles For son increíbles.

 17
Author: Bruce Dawson,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-09-20 05:52:47