Table manipulation error - c++

I am trying to set a variable to the value of an element of a 2D array. This should be easy, but whenever I write it I get 0 in the variable. I read in a file to put in the array elements manually, which might be causing the problem, but I am not sure what's wrong.
Here is my code:
int main(){
//declaring all the variables
vector < vector <double> > data; // vector of vectors to hold the data.
int z=0;
int z1,z2;
//open the input file as an input file stream (ifstream)
ifstream dataFile;
dataFile.open( "GBplaces.csv" );
//if the file is open...
if (dataFile.is_open()) {
// and while it's not the end of the file...
while (!dataFile.eof() ){
z++;
if (z==1){
string aLine;
getline ( dataFile, aLine );
printf ("place, type, population, lattitude, longitude \n\n");
}
else if(z==102){
string aLine;
getline ( dataFile, aLine );
}
else {
//read in a line of the file and put the ontents into the arays.
string aLine; // hold the read in line
getline ( dataFile, aLine ); //reads line from dataFile to aLine
//split up the string aLine based on where the comma is
int comma;
int nextCom=0;
//comma_pos = aLine.find(',',0); //finds where the comma is, starting from the begining ie 0
string xst, yst, zst; //temp variables for column
vector <double> temp; // tempory vector for the points
double xt, yt, zt;
comma = aLine.find(',',0); //find first position of comma
xst = aLine.substr(0,comma); // extracts string subvalue
temp.push_back(atof(xst.c_str())); //add value to end of temporary vector
comma += 1; // add 1 to the comma position count
while (aLine.find(',',comma) != -1) {
// find middle values
if(aLine==""){}
else{
nextCom = aLine.find(',',comma);
yst = aLine.substr(comma, nextCom - comma);
temp.push_back(atof(yst.c_str())); //convert string into double and add it to the end of the vector
comma = nextCom + 1;
}
}
// same calculations as in the loop but for the last value after the comma
zst = aLine.substr(nextCom + 1, aLine.length());
temp.push_back(atof(zst.c_str()));
// push temporary vector onto data vector
data.push_back(temp);
}
}
}
z = data[3][3].
When I run the program I get z=0, although when I print the table, the element is 51.26.

Update:
Found the error:
int z=0;
int z1,z2;
z1,z2 should be doubles instead of integers. This was messing up the rest of the number

Related

How to create a comma delimiter while reading from a vector?

I have two string vectors readData and commaSep. I want to read from vector readData and whenever I encounter a comma (,) I want to insert that data into commaSep without the comma. In my program readData has values like "xyz,22,pqr". My getline statement is wrong so suggest me something.
vector<string> readData; // has string values with ',' separation
vector<string> commaSep; // insert them in this vector
string temp;
for (int i = 0; i < readData.size(); i++) {
getline(readData[i], temp, ',');
commaSep.push_back({temp});
getline(readData[i], temp, ',');
commaSep.push_back({temp});
getline(readData[i], temp, '\n');
commaSep.push_back({temp});
}

inserting spaces function after char worked outside the code but inside return error in C++

I made a function inserting spaces after a specific char(s)
it works perfect for any long ,any char when separated.
like now
using namespace std;
insert_spaces_before_delims(string a)
{
vector<int> found;
int temp;
int i=0;
//string a="Ahmeed+Khaled+awwad=Ahmedd-AWWAd"; //string be a parameter
temp = a.find_first_of("+-="); // chars be parameters if need to change
found.push_back(temp);
a.insert(found[i]," ");
while(a.find_first_of("+-=",found[i]+2)!= string::npos)
{
temp = a.find_first_of("+-=",found[i]+2);
found.push_back(temp);
a.insert(found[i+1]," ");
i++;
}
}
int main(void)
{
string equation;
getline(cin,equation);
insert_spaces_before_delims(equation);
//the output is the string with spaces before every +,- and =
}
i debug the function when returns that error
"terminate called after throwing an instance of 'std::out_of_range'
what(): basic_string::replace: __pos (which is 4294967295) > this->size() (which is 0)"
by condition (==string::npos)
why it comes again in the code and stop the code from continue , just return the error and end the program.
struct variable_content
{
//string coefficient; // coefficient of x ( value before x)
int value; // value of X = coefficient but in another type
string order; // order (number ) of x (number after x)
};
spilit__each_string(string,char,variable_content,vector<string>,vector<variable_content>);
spliting_each_variable(char ,variable_content ,vector<string> ,vector<variable_content>);
insert_spaces_before_delims(string );
int main()
{
int number_equations;
string equation; //receive string
vector<string> equations; // vector for equations input from user
vector<string> variables; // initial empty vector of string for each var as strings at all
vector<variable_content> variable; //initial empty vector of struct for each var
char delim[] = " ";
char delim1[]="xX";
cin>>number_equations;
number_equations++;
variable_content temp;
for (int i=0; i<number_equations;i++)
{
getline(cin,equation); //worked
//***the problem function , if i commented it the code works fine****
insert_spaces_before_delims(equation); //return error and stop the code
equations.push_back(equation); //worked
//make a temp struct and put tok1 in coefficient of it
spilit__each_string(equation, delim,temp,variables,variable);//worked
spliting_each_variable(delim1,temp ,variables,variable); //worked
}
//printing vector of struct of every variable
for(int y=0; y<variable.size();y++)
{
cout<<variable[y].value<<"\t"<<variable[y].order<<endl;
}
}
that the important parts
and the link of the whole code on github.https://github.com/AhmedKAwwad/Split-String-into-vector/blob/master/main.cpp
https://ericlippert.com/2014/03/05/how-to-debug-small-programs/
this link make me debug my code and found that having cin>> and getline mixed in my code do the error , then i use getline and then convert the string to integer
thanks for comments

How to know it's the end of the line in c++ reading file

I need to know how to stop if it's the end of the line
I need the int value for the last element which is 15
and also for the other lines, I need to know if this value is the last element in the line
i try getline(file ,line)
but it just gives me a string!
and also line.length(); gives me the length of the file.
You should either use std::getline and parse the string you get, or go char-by-char and treat CR/LF as end of line. Then just move back from it until you get a space.
You should continue to use your getline function, from that you will have your std::string then to pull your last digit use:
string str = <getline() result>
size_t last_index = str.find_last_not_of("0123456789");
string result = str.substr(last_index + 1);
int num = std::stoi(result);
This will give you your int representation of your last number.
This will extract the last number on each line:
ifstream f ("./numbers");
vector<int> v;
int i;
while (f >> i) {
char c = f.get();
if (f.eof() || c == '\r' || c == '\n') {
v.push_back(i);
}
}
f.eof() may be true if the file is not terminated by a new line, in which case the f.get() call may fail and set the eofbit.
std::ifstream file{"your-file"};
std::string line;
while (getline(file, line)) {
std::istringstream iss{line};
std::vector<int> vec{std::istream_iterator<int>{iss},
std::istream_iterator<int>{}};
if (vec.size() == 1) {
// only one element
}
vec.back() // last value of the line (/!\ check not empty first)
}

Reading a input file into a vector

I'm trying to read a file of int's and double's into a vector but I am having difficulty doing so. Given something like:
1 2.1 3 4
2 4
3
9 0.1
How can I use ifstream and the getline function to convert the string into integers and doubles & inserting this into a vector?
I know this is incorrect but I am thinking of something along the lines of:
vector<Pair *> vec; //Pair is a class that contains a int & a double data member
string str;
double num;
ifstream f;
f.open("name of file");
while(getline(f, str){
num = stod(str);
}
To insert into the vector I believe I can do something along the lines of:
Pair * pairObj = new Pair(x,y); //"x" being of type int and "y" being of type double
v.push_back(pair);
I'm sorry if this is unclear, please let me know and I will do my best to explain myself.
You should just use stream iterators!
#include <iostream> // for IO
#include <vector> // for vector!
#include <iterator> // for stream iterator
#include <algorithm> // for copy (optional)
if you are directly initializing
vector<double>vdata{istream_iterator<double>(ifile),
istream_iterator<double>()};
else use copy or copy_n if you only want a fixed amount of data
copy(istream_iterator<double>(ifile),
istream_iterator<double(),
back_inserter(vdata));
if you are working with a large file i would recommend using this method
vector<doube>vdata;
// this will save alot of time, if you don't resize the vector must keep reallocating data
vdata.reserve(file_size);
copy(istream_iterator<double>(ifile),
istream_iterator<double>(),
back_inserter(vdata));
strtod() is C. Proper C++ uses the >> operator.
Once you have read each line of text, construct a std::istringstream from the string, then use operator>> to parse it.
Something along these line::
std::ifstream f("name of file");
// Check if the file was succesfully opened, etc...
std::string str;
while( getline(f, str))
{
std::istringstream i(str);
std::vector<double> v;
double d;
while (i >> d)
{
v.push_back(d);
}
if (!i.eof())
{
// Must be a parsing failure, deal with it in some way.
}
else
{
// Otherwise, v is the vector of numbers on this line.
}
}
string str;
std::vector< double> vd;
// loop reading lines of input
while( getline( f, str )
{
std::stringstream sst(str);
std::string a;
// loop reading space separated values in line
while( getline( sst, a, ' ' ) )
// conver to double and add to end of vectior
vd.push_back( stod( a );
}
// check for complete pairs
if( vd.size() % 2 )
cout << "Error!"
// loop over pairs
vector< pair<int,double> > vpairs;
for( int kp = 0; kp < vd.size()/2; kp++ )
vpairs.push_back( pair<int,double>( (int)vd[kp*2],vd[kp*2+1) );

How can i pass comma separated values into a multidimensional array?

The text file provided has an undetermined number of lines, each line containing 3 doubles separated by commas. For example:
-0.30895,0.35076,-0.88403
-0.38774,0.36936,-0.84453
-0.44076,0.34096,-0.83035
...
I want to read this data from the file line by line and then split it on the comma(,) sign and save it in an N by 3 array, let's call it Vertices [N] [3], where N designates the undefined number of lines in the file.
My code so far:
void display() {
string line;
ifstream myfile ("File.txt");
if (myfile.is_open())
{
while ( getline (myfile,line) )
{
// I think the I should do 2 for loops here to fill the array as expected
}
myfile.close();
}
else cout << "Unable to open file";
}
The Problem: I managed to open the file and read line by line, but I have no idea how to pass the values into the requested array.
Thank you.
EDIT:
I have tried modifying my code according to the suggestions i received to the following:
void display() {
string line;
ifstream classFile ("File.txt");
vector<string> classData;
if (classFile.is_open())
{
std::string line;
while(std::getline(classFile, line)) {
std::istringstream s(line);
std::string field;
while (getline(s, field,',')) {
classData.push_back(line);
}
}
classFile.close();
}
else cout << "Unable to open file";
}
Is this the correct? and how can i access each field of the vector i created? (like in an array for example)?
I also noticed that these are of type string, how can i convert them to type float?
Thank you (:
There are many ways to approach this problem. Personally, I would implement a linked-list to save each line read out of the file in its own memory buffer. Once the entire file was read out, I would know how many lines were in the file and process each line in the list using strtok and strtod to convert the values.
Here's some pseudo code to get you rolling:
// Read the lines from the file and store them in a list
while ( getline (myfile,line) )
{
ListObj.Add( line );
}
// Allocate memory for your two-dimensional array
float **Vertices = (float **)malloc( ListObj.Count() * 3 * sizeof(float) );
// Read each line from the list, convert its values to floats
// and store the values in your array
int i = j = 0;
while ( line = ListObj.Remove() )
{
sVal = strtok( line, ",\r\n" );
fVal = (float)strtod( sVal, &pStop );
Verticies[i][j++] = fVal;
sVal = strtok( sVal + strlen(sVal) + 1, ",\r\n" );
fVal = (float)strtod( sVal, &pStop );
Verticies[i][j++] = fVal;
sVal = strtok( sVal + strlen(sVal) + 1, ",\r\n" );
fVal = (float)strtod( sVal, &pStop );
Verticies[i][j] = fVal;
i++;
j = 0;
}
The code after edit is right.You can access a vector value in c++ just like you access the values in a normal c++ array.Like classdata[i]You can find more here . Vector reference
And as for your question about converting string to float.In c++ you can directly do this by using stof ie stof(-0.883) you can find reference again here string to float
Best of luck and hope this helps :)