cout << "How many questions are there going to be on this exam?" << endl;
cout << ">>";
getline(cin, totalquestions);
This small piece of code comes from a function in a class that I have created and I need totalquestions
to be an int so that it can run through a for loop and keep asking the total amount of questions that I have asked.
question q;
for(int i = 0; i < totalquestions; i++)
{
q.inputdata();
questions.push_back(q);
}
Where does this piece of code comes to play? Does anyone have any idea to make this work?
getline() member function is used to extract string input. So it would be better if you input data in form of string and then use "stoi" (stands for string to integer) to extract only integer values from the string data.
The second method of declaring the C++ getline() function with two parameters is: istream& getline( istream& is, string& str ); In the above syntax, istream& getline is to define the function, and the three parameters are: istream& is: This is an istream class's object to specify the location to read the input stream.
One effective way to convert a string object into a numeral int is to use the stoi() function. This method is commonly used for newer versions of C++, with is being introduced with C++11. It takes as input a string value and returns as output the integer version of it.
Using std::getline() in C++ to split the input using delimiters. We can also use the delim argument to make the getline function split the input in terms of a delimiter character. By default, the delimiter is \n (newline). We can change this to make getline() split the input based on other characters too!
Use
cin >> totalquestions;
Check the errors too
if (!(cin >> totalquestions))
{
// handle error
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With