Reputation: 345
For example, I have a text file name example.txt. It has two columns.
12561 60295
13561 60297
13561 60298
13461 60299
15561 60300
15161 60301
15561 60302
14561 60316
12561 60317
10562 60345
15562 60346
15562 60347
15562 60348
15562 60362
19562 60363
11562 60364
12562 60365
15563 60408
15563 60409
75563 60410
65563 60411
14563 60412
13563 60413
I can read the text files following the macro:
#include <bits/stdc++.h>
using namespace std;
// driver code
int main()
{
vector<int> column1;
vector<int> column2;
fstream file;
string word, filename;
filename = "example.txt";
file.open(filename.c_str());
while (file >> word)
{
// displaying content
cout << word << endl;
}
return 0;
}
What I want to do is to push back the first column into the vector column1
, and the second column into vector column2
.
Therefore the output for vector 1 and 2 would be:
vector<int> column1 {12561,13561,13561,...}
vector<int> column2 {60295,60297,60298,...}
Upvotes: 1
Views: 1062
Reputation: 32586
just modify
while (file >> word)
{
// displaying content
cout << word << endl;
}
to have
int n1, n2;
while (file >> n1 >> n2) {
column1.push_back(n1);
column2.push_back(n2);
}
and remove the useless variable word, you can directly read numbers, you do not need to first read a string then get the number from it
Out of that I encourage you to check you was able to open the file to read it, else you cannot distinguish a file you cannot read (may be not existing) and an empty file
For instance :
#include <iostream>
#include <fstream>
#include <vector>
#include <cstring>
using namespace std;
// driver code
int main()
{
ifstream file("example.txt");
if (!file)
{
cerr << "cannot read the file example.txt :"
<< strerror(errno) << endl;
return -1;
}
vector<int> column1;
vector<int> column2;
int n1, n2;
while (file >> n1 >> n2) {
column1.push_back(n1);
column2.push_back(n2);
}
// display content to check
cout << "column1:";
for (auto v : column1)
cout << ' ' << v;
cout << endl << "column2:";
for (auto v : column2)
cout << ' ' << v;
cout << endl;
return 0;
}
Compilation and execution :
pi@raspberrypi:/tmp $ g++ -Wall r.cc
pi@raspberrypi:/tmp $ cat example.txt
12561 60295
13561 60297
13561 60298
13461 60299
15561 60300
15161 60301
15561 60302
14561 60316
12561 60317
10562 60345
15562 60346
15562 60347
15562 60348
15562 60362
19562 60363
11562 60364
12562 60365
15563 60408
15563 60409
75563 60410
65563 60411
14563 60412
13563 60413
pi@raspberrypi:/tmp $ ./a.out
column1: 12561 13561 13561 13461 15561 15161 15561 14561 12561 10562 15562 15562 15562 15562 19562 11562 12562 15563 15563 75563 65563 14563 13563
column2: 60295 60297 60298 60299 60300 60301 60302 60316 60317 60345 60346 60347 60348 60362 60363 60364 60365 60408 60409 60410 60411 60412 60413
pi@raspberrypi:/tmp $ chmod -r example.txt
pi@raspberrypi:/tmp $ ./a.out
cannot read the file example.txt : Permission denied
pi@raspberrypi:/tmp $
Upvotes: 1