Reading Line from Text File and Putting the Strings into a Vector

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

@FailedDev did, indeed, list the simplest form. 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";
}
}

Read .txt file and put each line into vectors

You should create a vector of vectors. This way you can refer to each individual vector using an index.

How do you create vectors with different names in a for loop

How do you read a text file into a vector in c++?

This vector:

vector <int> list = {};

Has exactly zero members. You never try and increase its size so any access to this array will result in a bad result.

There are a couple of places you accesses this vector:

input>>list[i];

// and

cout<<list[k];

These are both invalid access to the list.

To fix the problem you can read the data into a value and then append it to the vector:

int value;
input >> value;
list.emplace_back(value); // emplace back expands the vector by one place.

But that is not your only problem:

 while (i <= count_line() && count_line() > 0){

This while statement contains to calls that open a file parse the whole file and return a count. I doubt the compiler can optimize that away so that is exceedingly expensive call to make.

Can you just read values until there are none left?

 int   value;
while(input >> value) {
list.emplace_back(value);
}

But the proper way to do this:

 #include <vector>
#include <iterator>
#include <iostream>
#include <fstream>

int main()
{
std::ifstream file("text.txt");
std::vector<int> data(std::istream_iterator<int>{file},
std::istream_iterator<int>{});

for(auto val: data) {
std::cout << val << " ";
}
std::cout << "\n";
}

Read file and input into vector

As already mentioned, std::getline and std::istringstream are good starting points.

Then you can use std::istream_iterator to create the vectors directly using the iterator overload of the std::vector constructor.

Perhaps something like this:

std::vector<std::vector<int>> read_file(std::istream& input)
{
std::vector<std::vector<int>> lines;

std::string line;
while (std::getline(input, line))
{
std::istringstream line_stream(line);

lines.emplace_back(std::istream_iterator<int>(line_stream),
std::istream_iterator<int>());
}

return lines;
}

This handles an arbitrary number of lines containing an arbitrary number of integer values.


Can be used something like this:

int main(int, char* argv[])
{
std::ifstream input(argv[1]);
auto data = read_file(input);

std::cout << "First line of data: ";
for (auto value : data[0])
{
std::cout << value << ' ';
}
std::cout << '\n';

std::cout << "Second line of data: ";
for (auto value : data[1])
{
std::cout << value << ' ';
}
std::cout << '\n';
}

Important note: The example above lacks any kind of error or range checking. It's left as an exercise for the reader.



Related Topics



Leave a reply



Submit