My c++ program asks for input of a integer type if the user inputs a character/string then the program crashes is there another method for this or another way to fix it thank you.

Recommended Answers

All 3 Replies

Yes, you can get your input into a string and parse it.

#include <string>
#include <sstream>
#include <iostream>
using namespace std;

int main()
{
  string input;
  getline(cin,input);
  int value = 0;
  stringstream(input) >> value;
  if(value == 0)
     cout << "Invalid entry." << endl;
  cout << value << endl;
}

Yes, you can get your input into a string and parse it.

#include <string>
#include <sstream>
#include <iostream>
using namespace std;

int main()
{
  <snip>
  stringstream(input) >> value;
    <snip>
}

if that fails, stringstream throws and error so testing for 0 value is not a good option. And what happens if the input is actually 0?

didn't know that. thanks.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.