hi, i think i am stuck on a piece of code i am doing. i have a text file which i am reading from. i want to take out only the non zero values from the file and place it along with its coordinates in a vector.
the text file is separated into two sections based on a blank line between values. when i reach this blank line i want to start saving the remaining non zero values in another vector. i am using the two vectors to later do calculation so output is only in my code at the moment to see if i am going along correctly so far.
here's my code if anyone can help point out errors in my code it would be greatly appreciated.
Code:
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
#include <fstream>
using std::string;
using std::stringstream;
using std::cin;
using std::endl;
using std::cout;
using std::vector;
using std::ifstream;
using std::getline;
struct info {
int num;
int co;
int ro;
};
vector<string> split(const string& line)
{
std::vector<string> ret;
stringstream ss(stringstream::in | stringstream::out);
ss << line;
string x;
while ( ss >> x){
ret.push_back(x);
}
return ret;
}
int main()
{
vector<info>matrix;
vector<info>matrix2;
info matri;
info matri2;
int count =0; int row2=0;
ifstream myfile("file.txt"); // open file
if ( !myfile ) { // is file found and opened?
cout << "Cannot find/open file" << endl;
return 1;
}
string x; int row=0;
while (getline(myfile,x)){
if(x.empty()){
break;
}
//row++;
std::vector<string> words = split(x);
// print out the words obtained
int count=0;
for ( int i =0; i != words.size(); ++i ){
int d;
//if(words[i] =="\n" ){
//break;
//}
d= atoi(words[i].c_str());
if(d!=0){
++count;
//myfile >> matri.sparse >> d >> i >> row;
d>>matri.num;
i>>matri.co;
row>>matri.ro;
matrix.push_back(matri);
//myfile.close;
for (int j = 0; j != count; ++j){
//cout<<count;
cout << "num:"<< d <<" col:"<< i<<" row:"<< row<< endl; //output all data
}
}
}
cout<<"cols:"<<i<<"\n"<<"\n";
++row;
}
cout<<"\n"<<"rows:"<<row<<"\n";
ifstream myfile2("file.txt");
if ( !myfile2 ) { // is file found and opened?
cout << "Cannot find/open file" << endl;
return 1;
}
string z;
while (!myfile2.eof()){
getline(myfile2,z);
while(!z.empty()){
getline(myfile2,z);
}
//row++;
while (!myfile2.eof()){
getline(myfile2,z);
std::vector<string> words = split(z);
// print out the words obtained
int count2=0;
for ( int c =0; c != words.size(); ++c ){
int b;
//if(words[i] =="\n" ){
//break;
//}
b= atoi(words[c].c_str());
if(b!=0){
++count;
//myfile >> matri.sparse >> d >> i >> row;
b>>matri2.num;
row2>>matri2.ro;
c>>matri2.co;
matrix2.push_back(matri2);
//myfile.close;
for (int k = 0; k != count2; ++k){
//cout<<count;
cout << "num2:"<< b <<" col2:"<< c<<" row2:"<< row2<< endl; //output all data
}
}
}
cout<<"cols2:"<<c<<"\n"<<"\n";
++row2;
}
cout<<"\n"<<"rows2:"<<row2<<"\n";
}
if (row!=row2 )
{
cout<<"these things cannot be added !"<<endl;}
return 0;
}