Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trying to use int in getline

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?

like image 672
Scott Avatar asked Apr 30 '11 20:04

Scott


People also ask

Can we use Getline for INT?

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.

What are the parameters for Getline?

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.

How do I convert a string to an int in C++?

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.

How do I use Getline with delimiter?

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!


1 Answers

Use

cin >> totalquestions;

Check the errors too

if (!(cin >> totalquestions))
{
    // handle error
}
like image 132
sehe Avatar answered Nov 09 '22 18:11

sehe