Write CSV file into vectors in C (continued) - c++

Basically I have 14800x8 matrix that has been extracted from matlab as CSV file ("moves.mo"). I need to read this file into 14800 vectors with 8 values each.
Here is a few lines from the file:
1,2,3,4,-1,-3,-2,-4
1,2,3,5,-1,-3,-2,-5
1,2,3,6,-1,-3,-2,-6
1,2,3,7,-1,-3,-2,-7
1,2,3,8,-1,-3,-2,-8
1,2,3,9,-1,-3,-2,-9
I wrote the following code:
#include <iostream>
#include <fstream>
#include<stdio.h>
#include <string>
#include <istream>
#include <vector>
#include <sstream>
using namespace std;
int main()
{
std::fstream inputfile;
inputfile.open("moves.da");
std::vector< std::vector<int> > vectorsmovesList; //declare vector list
while (inputfile) {
std::string s;
if (!getline( inputfile, s )) break;
istringstream ss( s );
vector <int> recordmove;
while (ss)
{
if (!getline( ss, s, ',' )) break;
int recordedMoveInt = atoi(s.c_str());
recordmove.push_back( recordedMoveInt );
}
vectorsmovesList.push_back( recordmove );
}
if (!inputfile.eof())
{
cerr << "Fooey!\n";
}
It compiles but does not give me desirable output (i.e. just prints Fooey!) . I don't know why... This problem at this point is driving me insane.
Please help!

There are better ways to read integers in C++. For example:
std::string s;
if (!getline( inputfile, s )) break;
istringstream ss( s );
int recordedMove;
while (ss >> recordedMove)
{
recordmove.push_back(recordedMove);
// consume the commas between integers. note if there are no
// separating commas, you will lose some integers here.
char garbage;
ss >> garbage;
}
Also, you're not printing out your result anywhere. Here's how you would do it:
vector<vector<int> >::const_iterator ii;
for (ii = vectorsmovesList.begin(); ii != vectorsmovesList.end(); ++ii)
{
vector<int>::const_iterator jj;
for (jj = ii->begin(); jj != ii->end(); ++jj)
cout << *jj << ' ';
cout << endl;
}
Obviously, you'd do that after you've parsed and closed the CSV file.

Related

Copying read value from txt to a vector [duplicate]

I am attempting to write a program which can read in a text file, and store each word in it as an entry in a string type vector. I am sure that I am doing this very wrong, but it has been so long since I have tried to do this that I have forgotten how it is done. Any help is greatly appreciated. Thanks in advance.
Code:
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
using namespace std;
int main()
{
vector<string> input;
ifstream readFile;
vector<string>::iterator it;
it = input.begin();
readFile.open("input.txt");
for (it; ; it++)
{
char cWord[20];
string word;
word = readFile.get(*cWord, 20, '\n');
if (!readFile.eof())
{
input.push_back(word);
}
else
break;
}
cout << "Vector Size is now %d" << input.size();
return 0;
}
One of the many possible ways is a simple:
std::vector<std::string> words;
std::ifstream file("input.txt");
std::string word;
while (file >> word) {
words.push_back(word);
}
operator >> takes care of only words divided by whitespaces (including new-lines) being read.
And in case you would be reading it by lines, you might also need to explicitly handle empty lines:
std::vector<std::string> lines;
std::ifstream file("input.txt");
std::string line;
while ( std::getline(file, line) ) {
if ( !line.empty() )
lines.push_back(line);
}
#include <fstream>
#include <vector>
#include <string>
#include <iostream>
#include <algorithm>
#include <iterator>
using namespace std;
int main()
{
vector<string> input;
ifstream readFile("input.txt");
copy(istream_iterator<string>(readFile), {}, back_inserter(input));
cout << "Vector Size is now " << input.size();
}
Or, shorter:
int main()
{
ifstream readFile("input.txt");
cout << "Vector Size is now " << vector<string>(istream_iterator<string>(readFile), {}).size();
}
I'm not going to explain, because there's about a zillion explanations on StackOverflow already :)

How to get input an array of strings with \n as delimiter?

#include<bits/stdc++.h>
using namespace std;
int main()
{
int i=0;
char a[100][100];
do {
cin>>a[i];
i++;
}while( strcmp(a[i],"\n") !=0 );
for(int j=0;j<i;i++)
{
cout<<a[i]<<endl;
}
return 0;
}
Here , i want to exit the do while loop as the users hits enter .But, the code doesn't come out of the loop..
The following reads one line and splits it on white-space. This code is not something one would normally expect a beginner to write from scratch. However, searching on Duckduckgo or Stackoverflow will reveal lots of variations on this theme. When progamming, know that you are probably not the first to need the functionality you seek. The engineering way is to find the best and learn from it. Study the code below. From one tiny example, you will learn about getline, string-streams, iterators, copy, back_inserter, and more. What a bargain!
#include <iostream>
#include <string>
#include <sstream>
#include <algorithm>
#include <iterator>
#include <vector>
int main() {
using namespace std;
vector<string> tokens;
{
string line;
getline(cin, line);
istringstream stream(line);
copy(istream_iterator<string>(stream),
istream_iterator<string>(),
back_inserter(tokens));
}
for (auto s : tokens) {
cout << s << '\n';
}
return 0;
}
First of all, we need to read the line until the '\n' character, which we can do with getline(). The extraction operator >> won't work here, since it will also stop reading input upon reaching a space. Once we get the whole line, we can put it into a stringstream and use cin >> str or getline(cin, str, ' ') to read the individual strings.
Another approach might be to take advantage of the fact that the extraction operator will leave the delimiter in the stream. We can then check if it's a '\n' with cin.peek().
Here's the code for the first approach:
#include <iostream> //include the standard library files individually
#include <vector> //#include <bits/stdc++.h> is terrible practice.
#include <sstream>
int main()
{
std::vector<std::string> words; //vector to store the strings
std::string line;
std::getline(std::cin, line); //get the whole line
std::stringstream ss(line); //create stringstream containing the line
std::string str;
while(std::getline(ss, str, ' ')) //loops until the input fails (when ss is empty)
{
words.push_back(str);
}
for(std::string &s : words)
{
std::cout << s << '\n';
}
}
And for the second approach:
#include <iostream> //include the standard library files individually
#include <vector> //#include <bits/stdc++.h> is terrible practice.
int main()
{
std::vector<std::string> words; //vector to store the strings
while(std::cin.peek() != '\n') //loop until next character to be read is '\n'
{
std::string str; //read a word
std::cin >> str;
words.push_back(str);
}
for(std::string &s : words)
{
std::cout << s << '\n';
}
}
You canuse getline to read ENTER, run on windows:
//#include<bits/stdc++.h>
#include <iostream>
#include <string> // for getline()
using namespace std;
int main()
{
int i = 0;
char a[100][100];
string temp;
do {
getline(std::cin, temp);
if (temp.empty())
break;
strcpy_s(a[i], temp.substr(0, 100).c_str());
} while (++i < 100);
for (int j = 0; j<i; j++)
{
cout << a[j] << endl;
}
return 0;
}
While each getline will got a whole line, like "hello world" will be read once, you can split it, just see this post.

How to I delimit a string and store each part in different vectors

I have a text file that has many lines, an example is
john:student:business
may:lecturer:math
bob:student:math
how do i split them up and store them in different vectors such as:
vector1: john, may, bob
vector2: student, lecturer, student
vector3: business, math, math
my current code is:
ifstream readDetails(argv[1]);
while (getline (readEvents, line, ':')){
cout << line << endl;
}
it only splits the string up, but i could not think of any ways to separate the string and store them into vectors.
You can create a vector of vectors and play with the token index.
If the stream can sometimes have less tokens, you will need to handle that case.
#include <iostream>
#include <string>
#include <sstream>
#include <vector>
int main() {
const int NUM_TOKENS = 3;
std::vector<std::vector<std::string>> v(NUM_TOKENS);
int token = 0;
std::string str("Mary:Had:Lamb");
std::istringstream split(str);
std::string line;
while (std::getline (split, line, ':')){
v[token++].push_back(line);
if ( token == NUM_TOKENS )
token = 0;
}
return 0;
}
This can be done using a nested vector (aka 2D vector) and nested loops. The outer loop is for splitting the input into lines, the inner loop for splitting the tokens of each line which are separated by ':'.
#include <string>
#include <sstream>
#include <vector>
int main()
{
std::istringstream in{
"john:student:business\n"
"may:lecturer:math\n"
"bob:student:math"
};
std::vector< std::vector< std::string > > v{ 3 }; // Number of tokens per line
std::string line;
// Loop over the lines
while( std::getline( in, line ) ) {
std::istringstream lineStrm{ line };
// Loop to split the tokens of the current line
for( auto& col : v ) {
std::string token;
std::getline( lineStrm, token, ':' );
col.push_back( token );
}
}
}
Live demo on Coliru.
Create vectors of strings and store your data accordingly. Without using std::istringstream, you can basically take advantage of substr() and find() that come with String class, hence:
#include <iostream>
#include <string>
#include <fstream>
#include <vector>
using namespace std;
int main ()
{
ifstream inFile("data.txt");
string line;
vector<string> vStr1,vStr2, vStr3;
while( std::getline( inFile, line ) ){
string::size_type idx1 = line.find(":");
string::size_type idx2 = line.rfind(":");
vStr1.push_back(line.substr(0,idx1));
vStr2.push_back(line.substr(idx1+1,idx2-idx1-1));
vStr3.push_back(line.substr(idx2+1));
}
cout << "vector1: ";
for(int i(0); i < vStr1.size(); ++i ){
cout << vStr1[i] << " ";
}
cout << endl;
cout << "vector2: ";
for(int i(0); i < vStr2.size(); ++i ){
cout << vStr2[i] << " ";
}
cout << endl;
cout << "vector3: ";
for(int i(0); i < vStr3.size(); ++i ){
cout << vStr3[i] << " ";
}
cout << endl;
return 0;
}
The result is
vector1: john may bob
vector2: student lecturer student
vector3: business math math

How to parse table of numbers in C++

I need to parse a table of numbers formatted as ascii text. There are 36 space delimited signed integers per line of text and about 3000 lines in the file. The input file is generated by me in Matlab so I could modify the format. On the other hand, I also want to be able to parse the same file in VHDL and so ascii text is about the only format possible.
So far, I have a little program like this that can loop through all the lines of the input file. I just haven't found a way to get individual numbers out of the line. I am not a C++ purest. I would consider fscanf() but 36 numbers is a bit much for that. Please suggest practical ways to get numbers out of a text file.
int main()
{
string line;
ifstream myfile("CorrOut.dat");
if (!myfile.is_open())
cout << "Unable to open file";
else{
while (getline(myfile, line))
{
cout << line << '\n';
}
myfile.close();
}
return 0;
}
Use std::istringstream. Here is an example:
#include <sstream>
#include <string>
#include <fstream>
#include <iostream>
using namespace std;
int main()
{
string line;
istringstream strm;
int num;
ifstream ifs("YourData");
while (getline(ifs, line))
{
istringstream strm(line);
while ( strm >> num )
cout << num << " ";
cout << "\n";
}
}
Live Example
If you want to create a table, use a std::vector or other suitable container:
#include <sstream>
#include <string>
#include <fstream>
#include <iostream>
#include <vector>
using namespace std;
int main()
{
string line;
// our 2 dimensional table
vector<vector<int>> table;
istringstream strm;
int num;
ifstream ifs("YourData");
while (getline(ifs, line))
{
vector<int> vInt;
istringstream strm(line);
while ( strm >> num )
vInt.push_back(num);
table.push_back(vInt);
}
}
The table vector gets populated, row by row. Note we created an intermediate vector to store each row, and then that row gets added to the table.
Live Example
You can use a few different approaches, the one offered above is probable the quickest of them, however in case you have different delimitation characters you may consider one of the following solutions:
The first solution, read strings line by line. After that it use the find function in order to find the first position o the specific delimiter. It then removes the number read and continues till the delimiter is not found anymore.
You can customize the delimiter by modifying the delimiter variable value.
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int main()
{
string line;
ifstream myfile("CorrOut.dat");
string delimiter = " ";
size_t pos = 0;
string token;
vector<vector<int>> data;
if (!myfile.is_open())
cout << "Unable to open file";
else {
while (getline(myfile, line))
{
vector<int> temp;
pos = 0;
while ((pos = line.find(delimiter)) != std::string::npos) {
token = line.substr(0, pos);
std::cout << token << std::endl;
line.erase(0, pos + delimiter.length());
temp.push_back(atoi(token.c_str()));
}
data.push_back(temp);
}
myfile.close();
}
return 0;
}
The second solution make use of regex and it doesn't care about the delimiter use, it will search and match any integers found in the string.
#include <iostream>
#include <string>
#include <regex> // The new library introduced in C++ 11
#include <fstream>
using namespace std;
int main()
{
string line;
ifstream myfile("CorrOut.dat");
std::smatch m;
std::regex e("[-+]?\\d+");
vector<vector<int>> data;
if (!myfile.is_open())
cout << "Unable to open file";
else {
while (getline(myfile, line))
{
vector<int> temp;
while (regex_search(line, m, e)) {
for (auto x : m) {
std::cout << x.str() << " ";
temp.push_back(atoi(x.str().c_str()));
}
std::cout << std::endl;
line = m.suffix().str();
}
data.push_back(temp);
}
myfile.close();
}
return 0;
}

Initializing a vector from a text file

I am attempting to write a program which can read in a text file, and store each word in it as an entry in a string type vector. I am sure that I am doing this very wrong, but it has been so long since I have tried to do this that I have forgotten how it is done. Any help is greatly appreciated. Thanks in advance.
Code:
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
using namespace std;
int main()
{
vector<string> input;
ifstream readFile;
vector<string>::iterator it;
it = input.begin();
readFile.open("input.txt");
for (it; ; it++)
{
char cWord[20];
string word;
word = readFile.get(*cWord, 20, '\n');
if (!readFile.eof())
{
input.push_back(word);
}
else
break;
}
cout << "Vector Size is now %d" << input.size();
return 0;
}
One of the many possible ways is a simple:
std::vector<std::string> words;
std::ifstream file("input.txt");
std::string word;
while (file >> word) {
words.push_back(word);
}
operator >> takes care of only words divided by whitespaces (including new-lines) being read.
And in case you would be reading it by lines, you might also need to explicitly handle empty lines:
std::vector<std::string> lines;
std::ifstream file("input.txt");
std::string line;
while ( std::getline(file, line) ) {
if ( !line.empty() )
lines.push_back(line);
}
#include <fstream>
#include <vector>
#include <string>
#include <iostream>
#include <algorithm>
#include <iterator>
using namespace std;
int main()
{
vector<string> input;
ifstream readFile("input.txt");
copy(istream_iterator<string>(readFile), {}, back_inserter(input));
cout << "Vector Size is now " << input.size();
}
Or, shorter:
int main()
{
ifstream readFile("input.txt");
cout << "Vector Size is now " << vector<string>(istream_iterator<string>(readFile), {}).size();
}
I'm not going to explain, because there's about a zillion explanations on StackOverflow already :)