Please write a program about C++ For example This program about insert number :
ID: 3579194 • Letter: P
Question
Please write a program about C++
For example This program about insert number : 1 2 3 4 5 when I input number 10 is show 1 2 3 4 5 10 when i input A is show the number incorrect my program when i input number 200A , it is show 200 but it had to show "Incorrect number , enter number again : "
maybe use cin.clear() cin.get or
this my teacher' example
Explanation / Answer
If cin is reading integer, it stops when it encounters non numeral character, thus accepting inputs like 10111adaa, etc. Following code should do the job, we take input as string, check for non numeral characters, and then if correct, convert it to integer, else ask for input again:
#include <iostream>
#include <cstdlib>
using namespace std;
bool isInteger( string num, int &intValue ){
bool correctNumber = true;
for(int i = 0; i < num.size(); i++){
if( num[i] < '0' || num[i] > '9' ){
//this character is not numeral i.e. it is incorrect number
correctNumber = false;
}
}
if( correctNumber ){ //if it is a number, convert to type int
intValue = atoi( num.c_str() );
}
return correctNumber;
}
int main(){
string stringForOfInteger;
int actualInteger;
cout << "Please enter an integer: ";
cin >> stringForOfInteger;
while( !isInteger(stringForOfInteger, actualInteger) ){
cout << "Wrong Input. Try again: ";
cin >> stringForOfInteger;
}
cout << "Correct!!! You entered: " << actualInteger << endl;
}