This is my first time using stackoverflow. I've been unable to find out the information I need regarding getline. I'm in a simple programming class for engineering transfers so the code that we write is pretty simple. All i'm trying to do here is put a user-defined number of questions and answers into two different arrays. My while loop looks like this (I was using a for loop but switched to while just to see if it would stop breaking):
int main ()
{
srand((unsigned)time(0));
string quest1[100], answ1[100];
int size1, x = 0, num, count1, visit[100], shuffle[100];
fstream flashcard1;
cout << "flashcard.cpp by NAME\n" << endl;
cout << "This program allows user to manipulate questions and answers for studying.\n" << endl;
cout << "\nHow many flash cards will be entered(MAX 100)? ";
cin >> size1;
cout << endl;
while(x < size1)
{
cout << "Enter Question: ";
getline(cin , quest1[x]);
cout << endl;
x = x++;
/*
cout << "Enter Answer: " << endl;
getline(cin,answ1[x]);
cout << endl;
flashcard1.open("flashcard1.dat", ios::app);
flashcard1 << quest1[x] << " " << answ1[x] << endl;
flashcard1.close();
cout << "Data Stored." << endl;
*/
}
}
I noted out the answer entering part as well as the saving data to the file just for debugging. When I run the program it skips the getline for the first question, displays the second loop of "Enter question" and the getline works for the rest of them. So if I have a size1 of 5, the program only fills array positions 1-4. Please help. This is a simple flash card program that will do the same thing as if you were to create flash cards to study and shuffle them.
x = x++;
is Undefined Behaviour. It should just bex++
(or++x
, orx += 1
, orx = x + 1
, orx -= -1
....) – Pickardendl
when you mean'\n'
.std::cout << std::endl
is precisely equivalent tostd::cout << '\n' << std::flush
. 2) Never say "using namespace std;", ever, even if (especially if) your book or professor tell you to. Importing the entirestd
namespace into your program creates hard-to-identify bugs. – Firoocusing namespace std;
. As long as you know what the dangers are, you can do it in very controlled environments (like one-file short programs for example). – Pickard