+ 1
is there a short method of taking only integers from the user neglecting "sting content" in C++?
for me i take the input from the user on a string variable then i convert it to int by stringstream class, is there a shorter published way for this purpose??
7 Respuestas
+ 4
int x;
cin >> x;
Only problem is that it will return error if input isn’t an integer.
+ 2
@Jacob yea that's the main thing, and the stream will be broken one the user enters a text instead of integer.
+ 2
you can do what Jacob said and use cin.good(), it checks if the input was correct, so put cin >> x; in infinity loop, write if(!cin.good()) and inside cin.clear() and print something like "Wrong input", and else break;
it may also be needed to put cin.ignore() or cin.ignore(1000, '/n') inside if.
this way it will ask for an input until correct int will be put
+ 2
@HaYyan JarBoue
Apparently I (somehow) deleted my reply by accident. In any case it doesn't matter. I wrote the example using std::string (and I'll rewrite it for you in case you don't remember), but you can use C-style strings if you want. The way you obtain the string is irrelevant, as all it does is remove all characters which aren't numbers.
#include <iostream>
#include <cstdlib>
#include <cctype>
//write "using namespace std" if you don't want to write std:: a bunch
int StringToNumber(const char *input_c_string)
{
std::string input_string (input_c_string);
std::string output_string (input_string.lenght(), '\0');
int j=0;
for (int i=0; i<input_string.lenght(); ++i) {
if (std::isalphanum(input_string.at(i))
&& !std::isalpha(input_string.at(i))) {
output_string.at(j) = input_string.at(i);
++j;
}
}
return std::atoi(output_string.c_str);
}
There you go, read the input using whatever method you want. If you are using c-style strings just pass it. If you are using std::string pass a.c_str, where a is the name of the string.
+ 1
@vlad thank you for your answer but could you please tell me which input method will i have to use in this way? is it cin>> or scanf or it doesn't matter?
+ 1
i think only cin
+ 1
@Vlad thanks alot i really appreciate it 👌