0

I have a user input an integer... But if it's really long, it throws an exception and starts looping infinitely. How would I make it cut the number after the first 7 digits and only use that? Like, if I inputted 654897654321648435435135813513843513543514, it would only accept 6548976. Please help.

3
Contributors
4
Replies
5
Views
6 Years
Discussion Span
Last Post by firstPerson
0

As suggested the easiest way to achieve it is using std::string as follows:

std::string getClampedInput(const int maxSize){
 string str;
 getline(cin,str);
 int clampedSize = maxSize > str.size() ? str.size() : maxSize; //make sure maxSize is not greater than input size
 return str.substr(0,maxSize);
}

another way is to do it is using cin.get, but the above method is the easiest.

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.