Re: Read data into c++
axcytz@gmail.com wrote:
I have a data that looks like this:
1,2,3
1,3,4
2,4
1
2,4,5,6
I have these data in an excel file but can also copy into a txt file. I have
declared a vector in c++ and want to read these data into my c++ code.
How can I import these data from txt or excel file?
For those kind of things, use a standard input stream and tell it that "," has
to be considered as a "white space". The key point is std::istream::imbue.
Below is an example:
#include <iostream>
#include <fstream>
#include <sstream>
#include <iterator>
#include <string>
#include <vector>
#include <cctype>
#include <locale>
#include <vector>
#include <algorithm>
using namespace std;
vector<int> get_vector(istream& is) {
istream_iterator<int> ii(is), eof;
return vector<int>(ii, eof);
}
void print_vector(const vector<int>& v) {
ostream_iterator<int> oo(cout, "\n");
copy(begin(v), end(v), oo);
}
struct Facet : ctype<char> {
Facet() : ctype<char>(get_table()) {}
static ctype_base::mask const* get_table() {
static vector<ctype_base::mask>
rc(classic_table(), classic_table() + table_size);
for (size_t i = 0; i < table_size; i++)
if (i == ',')
rc[i] = ctype_base::space;
return &rc[0];
}
};
int main(int argc, char** argv) {
istream* in = &cin;
if (argc == 2)
in = new ifstream(argv[1]);
istringstream istr;
istr.imbue(locale(locale(), new Facet())); // the facet will be destroyed
for (string line; getline(*in, line); istr.clear()) {
istr.str(line);
vector<int> v = get_vector(istr);
print_vector(v);
}
if (in != &cin)
delete in;
return 0;
}