Hi there, I'm reading data from a file into a vector of strings called data
. And to this data vector I push_back a new string through my main called output_string
. Output_string is just a combination of the arguments passed in through command line. After doing all that I write back to my file(update the file with the new string). However when I do this, everything after the 1st command line argument,it skips a vector position whenever it encounters data.push_back(output_string);
again.
eg file contents
bob
jack
snack
after reading into vector,
data vector contents
bob
jack
snack
after adding new string, new string being "john" data vector contents become
bob
jack
snack
john
but if i Run the program again and use command line to add something again it skips one vector position
bob
jack
snack
john
peter
and it does this for everything that I add after the first. Why is doing this?
int main (int argc, char *argv[]){
if (argc > 6){
cout<<"[Error] too many inputs provided" << endl;
return 0;
}
commandProcess(argc,argv);
outputstringformat();
//*********
if (cominput.rem_contpos == -1){
readData(); //reads data from a file into vector data
int outlen = output_string.length();
if (outlen > 0){
data.push_back(output_string); //pushing what i had in argv to vector
}
cout<<"----------data vector------------"<<endl;
for (int i = 0; i < data.size();i++){
cout<<"data: " << data[i] << endl;
}
ofstream outfile("contactlist.dat");
number_of_contacts = data.size();
if(outfile.is_open()){
for (int i =0; i < number_of_contacts; i++){
outfile << data[i] << endl; //copying evertthing back to file, including the new argument passed to data
}
outfile.close();
}
}
return 0;
}
EDIT: also this is how I process my arguments, I combine them into a single string. I have an inkling this could be the issue but still don't see it... :|
void outputstringformat(){
if (cominput.name1.length() != 0 ){
output_string = cominput.name1;
}
if (cominput.name2.length() != 0 ){
output_string = output_string + " " + cominput.name2;
}
if (cominput.name3.length() != 0 ){
output_string = output_string + " " + cominput.name3;
}
if (cominput.email.length() != 0 ){
output_string = output_string + " " + cominput.email;
}
if (cominput.phone.length() != 0 ){
output_string = output_string + " " + cominput.phone;
}
}
updated with reaData
void readData(){
ifstream myfile("contactlist.dat");
if(myfile.is_open()){
while(!myfile.eof()){
getline(myfile,line);
data.push_back(line);
}
myfile.close();
}
}