I try to identify if a number is an interger or not.
When I run this, I enter a number, such as 5.5, it shows "5.5 is not int. Please try again: ". Then I enter the letter, such as 'a', it shows "5.5 is not int. Please try again: ". The letter 'a' is a character, not integer, I think it should go to the second case and must show "No letter please", but it isn't.
When I first enter a letter, such as 'D', the program run "Please no letter" unlimited times. I wants it shows "Please no letter" but only once, then I can enter another number in this loop.
How can I fix these errors?
while (true) {
while ((num) != static_cast<int>(num)) {
cout << "\t" << num << " is not int. Please try again: ";
cin >> num;
cin.clear();
cin.ignore(80, '\n');
}
while (!(cin >> num)) {
cout << "\tNo letter please: ";
cin >> num;
cin.clear();
cin.ignore(80, '\n');
}
cout << "Good! " << num << " is an int!\n\n";
}
You can do in this way. Enter a string from user. Count the number of characters in that string. If that is equal to string length it is a valid positive integer. For negative integers just check if the number of digits is one less than size of string and string is starting with 0.
#include <iostream>
using namespace std;
int main()
{
string s;
while(true)
{
cin>>s;
int i,no_of_digits=0;
for(int i=0;i<s.length();i++)
{
if(isdigit(s[i]))
no_of_digits++;
}
if(no_of_digits == s.length() || (no_of_digits == s.length()-1 && s[0]=='-'))
{
cout<<"Good "<<s<<" is an Integer.";
break;
}
cout<<s<<" is not a valid Integer!\nPlease Enter again\n";
}
return 0;
}
The best way to parse string in cpp. It's to use stringstream or use sto* series functions of cpp11.
There are already some good answer here.
Related
I need to check whether digit was entered and if not, ask for correct input.
Second input is ignored for some reason.
(There should be "while" instead of "if" in the final version, but I replaced it to "if" for debug to avoid eternal loops)
#include <iostream>
int main()
{
int number = 0;
std::cout << "Please enter some digit:\n";
std::cin >> number;
if (!isdigit(number))
{
std::cout << "Wrong input, please enter digit\n";
std::cin >> number;
}
}
There is no point in using isdigit() on an int, it only makes sense to use it with a char, as it looks for characters between '0'..'9', not integers between 0..9.
If cin >> number fails to read in a valid integer, it will put the stream into a failure state, which blocks further input. You must clear() that state, and also ignore() the erroneous input, before you can read in further input.
Try something more like this:
#include <iostream>
#include <limits>
int main()
{
int number;
std::cout << "Please enter a single digit:\n";
do
{
if (std::cin >> number)
{
if (number >= 0 && number <= 9)
break;
std::cout << "Wrong input, please enter a single digit\n";
}
else
{
std::cout << "Wrong input, please enter a valid digit\n";
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}
}
while (true);
std::cout << "You entered: " << number << std::endl;
}
I want to check if the input is valid, but when i do run this code I see that it checks only input for charcters. If i input a float number it will take it and going to use like integer without fractional part.
#inclide <iostream>
using namespace std;
...
int n;
cout << "Your input is: "<<endl;
cin >> n;
while (cin.fail()) {
cout << "Error. Number of elements must be integer. Try again: " << endl;
cin.clear();
cin.ignore(256, '\n');
cin >> n;
}
...
`
So, how to make this code see if the input is float?
You can try to convert the input string to a int using a std::istringstream. If it succeeds then check for eof() (after ignoring blank spaces) to see if the whole input was consumed while converting to int. If the whole input was consumed then it was a valid int.
Something a bit like this:
int input_int()
{
int i;
// get the input
for(std::string line; std::getline(std::cin, line);)
{
// try to convert the input to an int
// if at eof() all of the input was converted - must be an int
if(!line.empty() && (std::istringstream(line) >> i >> std::ws).eof())
break;
// try again
std::cout << "Not an integer please try again: " << std::flush;
}
return i;
}
int main()
{
std::cout << "Enter an integer: " << std::flush;
std::cout << "i: " << input_int() << '\n';
}
Building on Raindrop7's solution, here's the full code to do what you need:
#include <cstdio>
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
double m;
cout << "Your input is: "<<endl;
cin >> m;
while (cin.fail() || (m-floor(m)))
{
cout << "Error. Nubmer of elements has to be integer. Try again: " << endl;
cin.clear();
cin.ignore(256, '\n');
cin >> m;
}
int n = (int)m;
return 0;
}
Here's a sample output:
Your input is:
2.7
Error. Nubmer of elements has to be integer. Try again:
erer
Error. Nubmer of elements has to be integer. Try again:
2
The code below should be able to do what you are hoping to achieve:
#inclide <iostream>
using namespace std;
int n;
cout << "Your input is: "<<endl;
while (!(cin >> n) || cin.get() != '\n') {
cout << "Error. Number of elements must be integer. Try again: " << endl;
cin.clear();
cin.ignore(256, '\n');
}
The program asks the user to re-enter an integer if either of the following happens:
If the program is unable to extract an integer from the std::cin stream. (For example, when a character or string is entered by the user)
If, after an integer is extracted successfully, the next character in std::cin is not the new line '\n' character. (For example, when a number with a decimal point like 1.1 is entered, or when an integer followed by a character like 1a is entered.)
I am writing a code for class that asks the user to input a size that is an odd number equal to or greater than 7. I have been able to make that part of my code work successfully. However, the next part consists of asking the user to enter a specific letter, in this case 'c'. If they do not enter 'c' then the loop should ask them to input another character. Whenever I run this code, it is creating an infinite loop whether I enter 'c' or another letter. I think my expression in my second while loop is incorrect, but I haven't been able to find a lot of information regarding this that could help me.
#include <iostream>
using namespace std;
int main() {
int s, l;
cout << "Welcome to the letter printer." << endl;
cout << "Enter the size: " << endl;
cin >> s;
while (s < 7 || s%2==0 || s<0)
{
cout << "Invalid size. Enter the size again: " << endl;
cin >> s;
}
cout << "Enter the letter: " << endl;
cin >> l;
while (l != 'c')
{
cout << "Invalid letter. Enter the letter again: " << endl;
cin >> l;
}
return 0;
}
because you are getting char for int variable
wrong:
int s, l;
right one:
int s;
char l;
what is why it goes on infinite loop in second while
explanation for infinite loop
This is how basic_istream works. In your case when cin >> l gets
wrong input - failbit is set and cin is not cleared. So next time it
will be the same wrong input. To handle this correctly you can add
check for correct input and clear&ignore cin in case of wrong input.
incorporated from here
If the input is an integer, I want to set it equal to an integer variable.
If the input is a string, I will want to set it to a string variable, and later check if the string is "quit".
I don't know how to check it. I've looked for a built in function and found nothing.
while (true) {
int numberEntered;
string stringEntered;
cout << "enter a number to see if it is greater than 5: \n or enter \'quit\' to exit the program";
//I don't know what to do below here
cin >> ;
if (stringEntered == "quit") {
break;
}
if (numberEntered > 5) {
cout << "that number is greater than 5" << endl;
}
else {
cout << "not greater than 5" << endl;
}
}
cin >> numberEntered;
if (!cin.fail())
{
...
It may be more idiomatic to use:
if (cin >> numberEntered)
David S.'s answer is good. If you want to tidily handle garbage being entered after the line, here is another option (this is more complicated for your situation, but if you later want to expand your program to handle a lot of different input, then this way may come out to be simpler).
while( true )
{
string stringEntered;
cout << "enter a number to see if it is greater than 5: \n or enter \'quit\' to exit the program: " << flush;
// read the whole line, this ensures no garbage remains in the input stream
getline(cin, stringEntered);
if ( stringEntered == "quit" )
break;
// this checks that a number was entered and nothing else
istringstream iss(stringEntered);
int numberEntered;
char ch;
if ( !(iss >> numberEntered) || (iss >> ch) )
{
cout << "please try again. ";
continue;
}
// process the number
cout << "that number is " << (numberEntered > 5 ? "" : "not ")
<< "greater than 5." << endl;
}
You may need #include <sstream>.
I am trying to make a cin where the user can only enter 0 to 1. If the user doesnt enter those numbers then he should get an error saying "Please enter within the range of 0 to 1."
But its not working.
What am i doing wrong?
int alphaval = -1;
do
{
std::cout << "Enter Alpha between [0, 1]: ";
while (!(std::cin >> alphaval)) // while the input is invalid
{
std::cin.clear(); // clear the fail bit
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); // ignore the invalid entry
std::cout << "Invalid Entry! Please Enter a valid value: ";
}
}
while (0 > alphaval || 1 < alphaval);
Alpha = alphaval;
Try this:
int alphaval;
cout << "Enter a number between 0 and 1: ";
cin >> alphaval;
while (alphaval < 0 || alphaval > 1)
{
cout << "Invalid entry! Please enter a valid value: ";
cin >> alphaval;
}
If you want to trap empty lines I'd use std::getline and then parse the string to see if the input is valid.
Something like this:
#include <iostream>
#include <sstream>
#include <string>
int main()
{
int alphaval = -1;
for(;;)
{
std::cout << "Enter Alpha between [0, 1]: ";
std::string line;
std::getline(std::cin, line);
if(!line.empty())
{
std::stringstream s(line);
//If an int was parsed, the stream is now empty, and it fits the range break out of the loop.
if(s >> alphaval && s.eof() && (alphaval >= 0 && alphaval <= 1))
{
break;
}
}
std::cout << "Invalid Entry!\n";
}
std::cout << "Alpha = " << alphaval << "\n";
return 0;
}
If you want a different prompt on error then I'd put the initial prompt outside the loop and change the inner prompt to what you prefer.
Week one of C++, starting with Peggy Fisher's Learning C++ on Lynda.com.
This is what I came up with. Love to receive feedback.
int GetIntFromRange(int lower, int upper){
//variable that we'll assign input to
int input;
//clear any previous inputs so that we don't take anything from previous lines
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
//First error catch. If it's not an integer, don't even let it get to bounds control
while(!(cin>>input)) {
cout << "Wrong Input Type. Please try again.\n";
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
}
//Bounds control
while(input < lower || input > upper) {
cout << "Out of Range. Re-enter option: ";
cin.ignore(numeric_limits<streamsize>::max(), '\n');
//Second error catch. If out of range integer was entered, and then a non-integer this second one shall catch it
while(!(cin>>input)) {
cout << "Wrong Input Type. Please try again.\n";
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
}
}
//return the cin input
return input;
}
As the exercise was to order Hamburgers, this is how I ask for the amount:
int main(){
amount=GetIntFromRange(0,20);
}