C++ Even or Odd number program not working properly - c++

I'm new to C++, and I was doing the exercise found here:
http://www.learncpp.com/cpp-tutorial/32-arithmetic-operators/
I was doing quiz 2 which tells me co create a program that receives an integer from user, and prints true of that integer is even. So I created the following code:
#include "stdafx.h"
#include <iostream>
int getInteger()
{
std::cout << "Insert an integer" << "\n";
int8_t x;
std::cin >> x;
return x;
}
bool isEven(int8_t x)
{
bool b;
b = false;
std::cout << x % 2 << "\n";
if(x%2 == 0)
{
b = true;
}
return b;
}
void printResult(bool b)
{
std::cout << std::boolalpha;
std::cout << b << "\n";
}
int main()
{
int8_t x;
x = getInteger();
bool b;
b = isEven(x);
printResult(b);
return 0;
}
So, here is the problem. Unless I'm missing something, this should work, right? And it does, but only for integers that I input from 0 to 10. For some reason, if I input 10, or 12, it prints false, but it works fine with 2, 4, 6, and 8. Why is this happening?

You have following code:
int8_t x;
std::cin >> x;
int8_t is just an alias for char for your platform and std::istream when it has type char as argument inputs one character, not integer. So solution would be to use type int and you should use it from the beginning as there is no reason at all to use int8_t in this case.

This function returns a different type than the one it supposed to return:
int getInteger()
{
std::cout << "Insert an integer" << "\n";
int8_t x;
std::cin >> x;
return x;
}
int should work fine instead of int8_t and see here why Documentation

As you have it getInteger() takes character text translated input, not numbers., since int8_t actually expands to char
To fix that take a integer number in 1st place and cast to the int8_t type:
int getInteger()
{
std::cout << "Insert an integer" << "\n";
int x; // <<<<
std::cin >> x;
return x;
}
x = (int8_t)getInteger();

The reason that Alex on learncpp.com specifies that it is better to use fixed width integers is because the results of the program will not vary when it is compiled on different compilers. This is not the case for non-fixed-width integral types like char and int, since the size of the type will vary between compilers. As #Slava points out, int8_t is a fixed width integral type for char, so both are used with variables that will only store a single character in memory.
Use fixed width integers whenever the program may be used in a different compiler or machine and it is important that the results will be compiler- and platform-independent. Because the program is asking for user input for any integer, to use a fixed width integer, it would be best to use int32_t. int8_t and 'char' would be suitable for getting digits (i.e. 0–9). int16_t is suitable for integers between -2^16/2 (which equals -2^15) and 2^15-1 (i.e. between -32 768 and 32 767). 'int32_t' is suitable for integers between -2^31 and 2^31-1 (i.e. between -2 147 483 648 and 2 147 483 647).
As Alex explains later in 5.10 — std::cin, extraction, and dealing with invalid text input, it is important to handle all possible invalid user inputs.
Here is some updated code that will work, handle invalid user inputs, and loop to ask the user if they want to check whether another number is even or odd, and so do:
// StackOverflow C++ Even or Odd number program.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream> // for cin and cout
//include <cmath> // pow is no longer used and is commented out below.
#include <cstdint> // std::int32_t
// I changed the variable output for the function to int32_t, since that is the type being returned.
std::int32_t getInteger()
{
/* If you don't understand some parts, like do-while loops and
handling invalid user input, come back to it after learning it,
and just focus on what you can understand.
*/
// Use int32_t since the user input could potentially be a very large number.
std::int32_t x{ 0 };
bool notInt32t = 1;
bool cinFail{1};
do
{
// Don't use an '/n' character when getting user input, it makes more sense to get it on the same line as the prompt.
std::cout << "Enter an integer: ";
std::cin >> x;
cinFail = std::cin.fail();
if (cinFail)
{
std::cin.clear();
std::cin.ignore(32767, '\n');
std::cout << "Oops, that input is invalid. This may be because you entered a number larger \n";
std::cout << "than 2147483647 (which equals 2^31-1), or less than -2147483648 (which equals -2^31); \n";
std::cout << "or you did not enter an integer only. Please try again.\n";
}
// remove any extraneous input, which would otherwise be left in the buffer, causing unexpected results.
else
std::cin.ignore(32767,'\n');
/*Commented out because this will not work, it will fail to extract. Left in the code for education purposes.
notInt32t = ((x > (pow(2.0, 31.0) - 1)) || (x < -pow(2.0, 31.0)) || !(x % 1 == 0));
if (notInt32t)
std::cout << "Oops, you entered incorrectly!\n";
*/
} while (cinFail);
return x;
}
bool isEven(std::int32_t x)
{
bool isEven;
isEven = (x % 2 == 0) ?(true):(false);
return isEven;
}
/* I have commented this out and rewrote it, as it is ambiguous.
void printResult(bool b)
{
std::cout << std::boolalpha;
std::cout << b << "\n";
}*/
void printIsEven()
{
auto x = getInteger();
if (isEven(x))
std::cout << x << " is an even integer.\n";
else
std::cout << x << " is an odd integer.\n";
}
void printIsEvenLoop()
{
std::int8_t yOrN{};
bool isLoop{ true };
bool cinFail{ false };
bool isYOrN{ false };
while (isLoop)
{
do
{
std::cout << "Would you like to check whether another integer is even or odd?\n";
std::cout << "Enter y or n (yes or no): ";
std::cin >> yOrN;
cinFail = std::cin.fail();
if (cinFail)
{
std::cin.clear();
std::cin.ignore(32767, '\n');
std::cout << "Oops, that input is invalid! Please try again.\n";
}
// remove any extraneous input, which would otherwise be left in the buffer, causing unexpected results.
else
std::cin.ignore(32767, '\n');
isYOrN = ((yOrN == 'y' || yOrN == 'n'));
if (!isYOrN)
std::cout << "Oops, you entered incorrectly! Please try again.\n";
} while (cinFail || !isYOrN);
if (yOrN == 'y')
{
isLoop = true;
printIsEven();
}
else
isLoop = false;
}
}
int main()
{
printIsEven();
printIsEvenLoop();
return 0;
}

Related

When I input a number in char type, why i can't get a whole number?

I input a number in char type variable. like 12 or 22. but, console show me a 1 or 2.
How i get a whole number 12 ,22 in console?
#include <iostream>
int main()
{
using namespace std;
char a = 0;
cin >> a;
cout << a << endl;
return 0;
}
Here is console result.
12
1
C:\Users\kdwyh\source\repos\MyFirstProject\Debug\MyFirstProject.exe(프로세스 18464개)이(가) 종료되었습니다(코드: 0개).
이 창을 닫으려면 아무 키나 누르세요...
The reason I don't use int, string and something is because I want to get both number and Character in one variable.
So I want to see the results of combined numbers and character at the same time.
in that process i can't get a whole number.
#include <iostream>
using namespace std;
int index = 0;
constexpr int pagenum = 10;
void chapterlist(void);
void nextlist(void);
void beforelist(void);
void movechapter(char a);
int main(void)
{
char userin = 0;
bool toggle = 0;
cout << "결과를 볼 챕터를 고르시오." << endl;
chapterlist();
cout << "다음 페이지로 이동: n" << endl;
cin >> userin;
if (userin == 'n')
{
backflash:
while(toggle == 0)
{
nextlist();
cin >> userin;
if (userin == 'b')
{
toggle = 1;
goto backflash;
}
else if (userin == 'n')
continue;
else
{
system("cls");
movechapter(userin);
break;
}
}
while(toggle == 1)
{
beforelist();
cin >> userin;
if (userin == 'n')
{
toggle = 0;
goto backflash;
}
else if (userin == 'b')
continue;
else
{
system("cls");
movechapter(userin);
break;
}
}
}
else
{
system("cls");
movechapter(userin);
}
return 0;
}
void chapterlist(void)
{
int x = 0;
for (x = index + 1; x <= index + 10; x++)
cout << "Chapter." << x << endl;
}
void nextlist(void)
{
system("cls");
cout << "결과를 볼 챕터를 고르시오." << endl;
index = index + pagenum;
chapterlist();
cout << "다음 페이지로 이동: n" << endl;
cout << "이전 페이지로 이동: b" << endl;
}
void beforelist(void)
{
system("cls");
cout << "결과를 볼 챕터를 고르시오." << endl;
index = index - pagenum;
chapterlist();
cout << "다음 페이지로 이동: n" << endl;
cout << "이전 페이지로 이동: b" << endl;
}
void movechapter(char a)
{
cout << "선택한 Chapter." << a << "의 결과입니다." << endl;
}
In movechapter(), console show me a is 1 or 2, not 12, 22.
First, you have to understand what achar type is.
Character types: They can represent a single character, such as 'A' or '$'. The most basic type is char, which is a one-byte character. Other types are also provided for wider characters.
To simplify that, char can only hold one character.
Where as with your code, "12" is actually 2 separate characters, '1' and '2', and that's the reason it would not work.
Instead of declaring a as a char type, you could declare it as an int type, which is a type designed to hold numbers. So you would have:
int a = 0;
However, do note that int often has a maximum value of 2^31.
Or you could use std::string to store character strings. However, do note that if you wish to do any calculations to your string type, you would need to convert them to a number type first:
int myInt = std::stoi(myString);
Edit:
So I have re-checked your code after your update, there is nothing wrong with using std::string in your case. You can still check if user have input n or b by:
if (userin == "n")
Note that you would use double quotation mark, or "letter", around the content that you want to check.
On the other hand, you could use:
if(std::all_of(userin .begin(), userin.end(), ::isdigit))
To check if user have input a number.
Although char is just a number, it's presumed to mean "single character" here for input. Fix this by asking for something else:
int a = 0;
You can always cast that to char as necessary, testing, of course, for overflow.
You should be reading characters into a string, and then converting that string into an int. It would also probably make more sense to use something like getline() to read input, rather than cin >> a.
#include <string>
#include <iostream>
#include <stdexcept>
#include <stdio.h>
int main() {
std::string input_string;
/* note that there is no function that will convert an int string
to a char, only to an int. You can cast this to a char if needed,
or bounds check like I do */
int value;
while(1) {
getline(std::cin, input_string);
/* std::stoi throws std::invalid_argument when given a string
that doesn't start with a number */
try {
value = std::stoi(input_string);
} catch (std::invalid_argument) {
printf("Invalid number!\n");
continue;
}
/* You wanted a char, the max value of a `char` is 255. If
you are happy for any value, this check can be removed */
if (value > 255) {
printf("Too big, input a number between 0-255\n");
continue;
}
break;
}
printf("Number is %hhu\n", value);
}

Validating user input. Is The input an integer? C++ [duplicate]

I was typing this and it asks the user to input two integers which will then become variables. From there it will carry out simple operations.
How do I get the computer to check if what is entered is an integer or not? And if not, ask the user to type an integer in. For example: if someone inputs "a" instead of 2, then it will tell them to reenter a number.
Thanks
#include <iostream>
using namespace std;
int main ()
{
int firstvariable;
int secondvariable;
float float1;
float float2;
cout << "Please enter two integers and then press Enter:" << endl;
cin >> firstvariable;
cin >> secondvariable;
cout << "Time for some simple mathematical operations:\n" << endl;
cout << "The sum:\n " << firstvariable << "+" << secondvariable
<<"="<< firstvariable + secondvariable << "\n " << endl;
}
You can check like this:
int x;
cin >> x;
if (cin.fail()) {
//Not an int.
}
Furthermore, you can continue to get input until you get an int via:
#include <iostream>
int main() {
int x;
std::cin >> x;
while(std::cin.fail()) {
std::cout << "Error" << std::endl;
std::cin.clear();
std::cin.ignore(256,'\n');
std::cin >> x;
}
std::cout << x << std::endl;
return 0;
}
EDIT: To address the comment below regarding input like 10abc, one could modify the loop to accept a string as an input. Then check the string for any character not a number and handle that situation accordingly. One needs not clear/ignore the input stream in that situation. Verifying the string is just numbers, convert the string back to an integer. I mean, this was just off the cuff. There might be a better way. This won't work if you're accepting floats/doubles (would have to add '.' in the search string).
#include <iostream>
#include <string>
int main() {
std::string theInput;
int inputAsInt;
std::getline(std::cin, theInput);
while(std::cin.fail() || std::cin.eof() || theInput.find_first_not_of("0123456789") != std::string::npos) {
std::cout << "Error" << std::endl;
if( theInput.find_first_not_of("0123456789") == std::string::npos) {
std::cin.clear();
std::cin.ignore(256,'\n');
}
std::getline(std::cin, theInput);
}
std::string::size_type st;
inputAsInt = std::stoi(theInput,&st);
std::cout << inputAsInt << std::endl;
return 0;
}
Heh, this is an old question that could use a better answer.
User input should be obtained as a string and then attempt-converted to the data type you desire. Conveniently, this also allows you to answer questions like “what type of data is my input?”
Here is a function I use a lot. Other options exist, such as in Boost, but the basic premise is the same: attempt to perform the string→type conversion and observe the success or failure:
template <typename T>
auto string_to( const std::string & s )
{
T value;
std::istringstream ss( s );
return ((ss >> value) and (ss >> std::ws).eof()) // attempt the conversion
? value // success
: std::optional<T> { }; // failure
}
Using the optional type is just one way. You could also throw an exception or return a default value on failure. Whatever works for your situation.
Here is an example of using it:
int n;
std::cout << "n? ";
{
std::string s;
getline( std::cin, s );
auto x = string_to <int> ( s );
if (!x) return complain();
n = *x;
}
std::cout << "Multiply that by seven to get " << (7 * n) << ".\n";
limitations and type identification
In order for this to work, of course, there must exist a method to unambiguously extract your data type from a stream. This is the natural order of things in C++ — that is, business as usual. So no surprises here.
The next caveat is that some types subsume others. For example, if you are trying to distinguish between int and double, check for int first, since anything that converts to an int is also a double.
There is a function in c called isdigit(). That will suit you just fine. Example:
int var1 = 'h';
int var2 = '2';
if( isdigit(var1) )
{
printf("var1 = |%c| is a digit\n", var1 );
}
else
{
printf("var1 = |%c| is not a digit\n", var1 );
}
if( isdigit(var2) )
{
printf("var2 = |%c| is a digit\n", var2 );
}
else
{
printf("var2 = |%c| is not a digit\n", var2 );
}
From here
If istream fails to insert, it will set the fail bit.
int i = 0;
std::cin >> i; // type a and press enter
if (std::cin.fail())
{
std::cout << "I failed, try again ..." << std::endl
std::cin.clear(); // reset the failed state
}
You can set this up in a do-while loop to get the correct type (int in this case) propertly inserted.
For more information: http://augustcouncil.com/~tgibson/tutorial/iotips.html#directly
You can use the variables name itself to check if a value is an integer.
for example:
#include <iostream>
using namespace std;
int main (){
int firstvariable;
int secondvariable;
float float1;
float float2;
cout << "Please enter two integers and then press Enter:" << endl;
cin >> firstvariable;
cin >> secondvariable;
if(firstvariable && secondvariable){
cout << "Time for some simple mathematical operations:\n" << endl;
cout << "The sum:\n " << firstvariable << "+" << secondvariable
<<"="<< firstvariable + secondvariable << "\n " << endl;
}else{
cout << "\n[ERROR\tINVALID INPUT]\n";
return 1;
}
return 0;
}
I prefer to use <limits> to check for an int until it is passed.
#include <iostream>
#include <limits> //std::numeric_limits
using std::cout, std::endl, std::cin;
int main() {
int num;
while(!(cin >> num)){ //check the Input format for integer the right way
cin.clear();
cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
cout << "Invalid input. Reenter the number: ";
};
cout << "output= " << num << endl;
return 0;
}
Under C++11 and later, I have the found the std::stoi function very useful for this task. stoi throws an invalid_argument exception if conversion cannot be performed. This can be caught and handled as shown in the demo function 'getIntegerValue' below.
The stoi function has a second parameter 'idx' that indicates the position of the first character in the string after the number. We can use the value in idx to check against the string length and ascertain if there are any characters in the input other than the number. This helps eliminate input like 10abc or a decimal value.
The only case where this approach fails is when there is trailing white space after the number in the input, that is, the user enters a lot of spaces after inputting the number. To handle such a case, you could rtrim the input string as described in this post.
#include <iostream>
#include <string>
bool getIntegerValue(int &value);
int main(){
int value{};
bool valid{};
while(!valid){
std::cout << "Enter integer value: ";
valid = getIntegerValue(value);
if (!valid)
std::cout << "Invalid integer value! Please try again.\n" << std::endl;
}
std::cout << "You entered: " << value << std::endl;
return 0;
}
// Returns true if integer is read from standard input
bool getIntegerValue(int &value){
bool isInputValid{};
int valueFromString{};
size_t index{};
std::string userInput;
std::getline(std::cin, userInput);
try {
//stoi throws an invalid_argument exception if userInput cannot be
//converted to an integer.
valueFromString = std::stoi(userInput, &index);
//index being different than length of string implies additional
//characters in input that could not be converted to an integer.
//This is to handle inputs like 10str or decimal values like 10.12
if(index == userInput.length()) isInputValid = true;
}
catch (const std::invalid_argument &arg) {
; //you could show an invalid argument message here.
}
if (isInputValid) value = valueFromString;
return isInputValid;
}
You could use :
int a = 12;
if (a>0 || a<0){
cout << "Your text"<<endl;
}
I'm pretty sure it works.

why does my calculator program start flashing and scrolling when i enter a large number

my program is a calculator that currently only does addition and subtraction, but when i input a large number it starts flashing and scrolling. it works fine for small numbers. the program isn't long so here it is. a youtube video of the problem https://youtu.be/Fa03WtgXoek
#include <iostream>
int GVFU()
{
std::cout <<"enter number";
int a;
std::cin >> a;
return a;
}
int add()
{
int x = GVFU();
int y = GVFU();
int z = x + y;
std::cout <<z <<std::endl;
return 0;
}
int subtract()
{
int x = GVFU();
int y = GVFU();
int z = x - y;
std::cout <<z << std::endl;
return 0;
}
int main()
{
for ( ; ; )
{
std::cout << "enter 1 for addition and 2 for subtraction";
int c;
std::cin >> c;
if (c==1)
{
add();
}
if (c==2)
{
subtract();
}
std::cout << "press 1 to end";
int e;
std::cin >>e;
if (e==1)
{
return 0;
}
}
}
If you try to read a value from cin and the value read doesn't match the expected format, it causes the stream to fail and all future read operations will instantly return without reading anything.
Independently, in C++ integer values for the int type have a minimum and maximum possible value that depends on what compiler and system you're using. If you exceed that value when entering a number, cin will consider it a failed read.
Putting this together, once you enter a value that's too large, the program will keep running through the main loop in your program, prompting for a value, instantly returning without actually getting user input, then calculating garbage values.
To fix this, you'll need to either (1) just hope the user doesn't type in anything unexpected or (2) get user input more robustly. There are a number of good explanations about how to do option (2) here on Stack Overflow, and now that you know what the root cause of the issue is you can hopefully get the code fixed and working!
Use
std::cout << std::numeric_limits<int>::max() << std::endl;
and include #include <limits> and you will find out max int value on your machine.
int on your system is likely a 32-bit signed two's complement number, which means the max value it can represent is 2,147,483,647.
If you add bigger number stream will fail and all next read operations will return without reading anything.
Use unsigned long long which will allow you to insert bigger numbers.
You are taking your inputs as " int " and value range for int is between -2,147,483,648 to 2,147,483,647.
Which means that if you exceed this value 2,147,483,647 it can not be stored as an integer(int) type.
You should probably use Long data type for such large numbers.
You can add a following check in your code if the user input more than int limit
int GVFU()
{
std::cout <<"enter number";
int a;
std::cin >> a;
if(cin.fail())
{
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
cout << "Invalid input " << endl;
}
return a;
}
I would also add exit if invalid number
#include <iostream>
#include <cstdlib>
using namespace std;
int GVFU()
{
std::cout <<"enter number";
int a;
std::cin >> a;
if(cin.fail())
{
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
cout << "Invalid input " << endl;
std::exit(EXIT_FAILURE);
}
return a;
}
Note: You could also more info instead of just "Invalid input "
Output like size or limit info
enter 1 for addition and 2 for subtraction1
enter number4535245242
Invalid input
Program ended with exit code: 1

How to check if the input taken by the user doesn't contain decimal?

I am a newbie to C++. I have a situation where the input integer is taken from the user. However, I need to check if the user enters a decimal value. How do I check this?
I have tried cin.good(), cin.fail() but they are detecting only non-digit entries and not decimal numbers. Any help would be appreciated.
#include <iostream>
int main()
{
using namespace std;
int x;
cout << "Enter an integer: " << endl;
cin >> x;
if (cin.good()) {
cout << "input is an integer" << endl;
}
else
cout << "input is not an integer" << endl;
}
Here's my output:
1.
Enter an integer:
1.2
input is an integer
2.
Enter an integer:
a
input is not an integer
float x = 4.2;
if (x == (int) x)
{
// int
}
else
{
// not int
}
You can use std::isdigit for checking your string input next way.
bool is_numeric(const std::string& str)
{
std::string::const_iterator it = str.begin();
if (it != str.end() && *it == '-') ++it;
if (it == str.end()) return false;
while (it != str.end() && std::isdigit(*it)) ++it;
return it == str.end();
}
It's not hard to change it to work with floating points, if needs, but that function will exactly checks what you need.
You receive the input as an int from cin and hence any float entered would already be truncated by the time you get your hands on it. You should receive it as a float or a string to decide on the validity of the input.
Removed the earlier answer since it went down the slippery route of manually parsing the input which is unnecessary and error-prone. The standard library already has multiple ways to check if an input is a valid number. Two ways that I know: C++ streams and the C library function strtof. Here's an example using the latter:
#include <iostream>
#include <string>
#include <cmath>
bool is_int(float f) {
return std::floor(f) == f;
}
int main()
{
std::cout << "Enter an integer: ";
std::string input;
std::cin >> input;
char *e = nullptr;
char const *str = input.c_str();
float const f = strtof(str, &e);
// no conversion was performed or was stopped as disallowed
// characters were encountered: Not A Number
if ((e == str) || (*e != '\0'))
std::cout << "NAN";
else if ((f == HUGE_VALF) || !std::isfinite(f))
std::cout << "too large";
else
std::cout << (is_int(f) ? "integer" : "non-integer");
std::cout << '\n';
}
Live example.
To check if the input is a number, this
float f;
cin >> f;
is possible too, but it will also accept NANs as valid input e.g. 45dsf will be converted to 45. One has to then check if the conversion happened completely and successfully by checking the fail and eof bits of the stream.
See also
Checking if float is an integer
C++ IsFloat function
How to convert a number to string and vice versa in C++

How to make cin >> not convert float to integer?

I have the following simple code:
#include <iostream>
int main()
{
int a;
std::cout << "enter integer a" << std::endl;
std::cin >> a ;
if (std::cin.fail())
{
std::cin.clear();
std::cout << "input is not integer, re-enter please" <<std::endl;
std::cin >>a;
std::cout << "a inside if is: " << a <<std::endl;
}
std::cout << "a is " << a <<std::endl;
std::cin.get();
return 0;
}
When I run the above code and input: 1.5, it outputs: a is 1. FYI: I compile and run the code with gcc 4.5.3.
This means that if cin expects an integer but sees a float, it will do the conversion implicitly. So does this mean that when cin sees a float number, it is not in fail() state? Why this is the case? Is it because C++ does implicit conversion on >> operator?
I also tried the following code to decide whether a given input number is integer following idea from this post: testing if given number is integer:
#include <iostream>
bool integer(float k)
{
if( k == (int) k) return true;
return false;
}
int main()
{
int a;
std::cout << "enter integer a"<< std::endl;
std::cin >> a ;
if (!integer(a))
{
std::cout << "input is not integer, re-enter please" ;
std::cin.clear();
std::cin >> a;
std::cout << "a inside if is: " << a <<std::endl;
}
std::cout << "a is " << a <<std::endl;
std::cin.get();
return 0;
}
This block of code was also not able to test whether a is integer since it simply skip the if block when I run it with float input.
So why this is the case when getting user input with cin? What if sometimes I want the input to be 189, but typed 18.9 by accident, it will result in 18 in this case, which is bad. So does this mean using cin to get user input integers is not a good idea?
thank you.
When you read an integer and you give it an input of 1.5, what it sees is the integer 1, and it stops at the period since that isn't part of the integer. The ".5" is still in the input. This is the reason that you only get the integer part and it is also the reason why it doesn't seem to wait for input the second time.
To get around this, you could read a float instead of an integer so it reads the whole value, or you could check to see if there is anything else remaining on the line after reading the integer.
When reading user input I prefer not to use operator>> as user input is usally line based and prone to errors. I find it best to read a line at a time and validate:
std::string line;
std::getline(std::cin, line);
This also makes it easy to check for different types of numbers.
std::stirngstream linestream(line);
int val;
char c;
if ((linestream >> val) && !(linestream >> c))
{
// Get in here if an integer was read.
// And there is no following (non white space) characters.
// i.e. If the user only types in an integer.
//
// If the user typed any other character after the integer (like .5)
// then this will fail.
}
Of course boost already supports this:
val = boost::lexical_cast<int>(linestream); // Will throw if linestream does
// not contain an integer or
// contains anything in addition
// to the integer.
Boost of course will convert floats as well.
I have some snippet which is kind a poor coding, but it works.
This method is pretty simple, but doesn't handle case when input value is invalid.
See more: https://en.cppreference.com/w/cpp/string/byte/atof
static float InputFloat(std::string label)
{
std::string input;
std::cout << label;
std::cin >> input;
return atof(input.c_str());
}
int main()
{
float value = InputFloat("Enter some float value: ");
std::cout << "value = " << value;
return 0;
}