This is my first post to Stack Overflow, please forgive me if I have overlooked any formalities in the following post
I am currently writing a C++ program on Code::Blocks 17.12, using the GNU GCC Compiler. The program is for Exercise P6.4 of Big C++ 2nd Edition where I must write a function to append/combine two vectors worth of users input and then return the vector
I am able to enter the 1st vector just fine, but for some reason it won't allow me to enter the 2nd vector.
I have a feeling that the use of cin.fail() in the while loop is also triggered my 2nd bool value to immediately change to false. For this I added cin.clear(), hoping it would reset the stream to allow for the 2nd vector inputs, but to no avail.
Is it truly cin.fail() causing this error, or is it something else I am overlooking?
Edit: with the use of crtl-z, I am now able to get the 2nd vector, and run the program to completion, though the last element of the first vector a/a_vct is copying twice. Can you point me to some resources on the use of crtl-z to better understand its use? (haven't covered it in the book yet) ex. if i enter 1 2 3 for a_vct and 1 2 3 for b_vct, c_vct will output 1 2 3 3 1 2 3 0
#include <iostream>
#include <vector>
using namespace std;
vector<double>append(vector<double>a,vector<double>b)
{
vector<double>c; //combined vct
for (int i=0; i<a.size(); i++)
{
c.push_back(a[i]);
}
for (int i=0; i<b.size(); i++)
{
c.push_back(b[i]);
}
return c;
};
int main()
{
vector<double>a_vct; //inputs
vector<double>b_vct; //inputs
vector<double>c_vct; //appended vct
cout<<"Welcome to the vector append-er!"<<endl;
cout<<"Please enter 1st Vector (enter v to set vector after inputs):"<<endl;
bool v1_add=true;
while(v1_add)
{
double a;
cin>>a;
a_vct.push_back(a);
if(cin.fail()) //double usage is setting both bools to false???
{
v1_add=false;
}
}
cin.clear();
cout<<"Please enter 2nd Vector. Please enter the same number of elements (enter v to set vector after inputs):"<<endl;
bool v2_add=true;
while(v2_add)
{
double b;
cin>>b;
b_vct.push_back(b);
if(cin.fail())
{
v2_add=false;
}
}
c_vct=append(a_vct,b_vct);
cout<<"The appended vector is:"<<endl;
for (int i=0; i<c_vct.size(); i++)
{
cout<<c_vct[i]<<"";
}
return 0;
}
Edit 2: New changes as per the response, works as intended now
if(cin.good())
{
a_vct.push_back(a);
}
if(cin.good())
{
b_vct.push_back(b);
}