Reputation:
I have a problem in the if
clause I guess the code is correct but I don't know why there is a problem.
#include <iostream>
using namespace std;
int main()
{
int a;
cout<<"Enter a Number and we will tell you the loop"<<endl;
cin>>a;
{
if(a=char)
{
cout<<"Enter only Numbers"<<endl;
}
else
{
cout<<"The value is: ";<<a<<endl;
}
}
do
{
cout<<a<<endl;
a++;
} while(a<=10);
cout << "Hello world!" << endl;
return 0;
}
It would be great..Thanks
Upvotes: 0
Views: 2839
Reputation:
This is the solution for the question.
#include
using namespace std;
int main()
{
int a;
cout<<"Enter a Number and we will tell you the loop"<<endl;
cin >> a;
if(a) {
cout<<"The value is: "<<a<<endl;
}
else{
cout<<"Enter only Numbers"<<endl;
}
do{
cout<<a<<endl;
a++;
}while(a>=100);
cout << "Hello world!" << endl;
return 0;
}
Upvotes: 0
Reputation:
Like others have said, "a" will always be an int. cin.fail() in the below code can help you check for entry that is not a number and flag it.Hope this helps.
int a;
cout << " Enter a number" <<endl;
cin >> a;
while (cin.fail())
{
cout <<"Error. enter a number " << endl;
cin.clear();
cin.ignore();
cin >> a;
}
Upvotes: 1
Reputation: 64682
You cannot check the type of a variable by trying to compare a
and char
.
a
was declared an int
, and will always be an int
.
You don't need to check its type, you know what type it is.
If you truly want to accept any data, and then check to see if it can be converted to an int
, then you need to accept a string
, and try to parse that string:
int main()
{
string a;
cout << "Enter a Number and we will tell you the loop" << endl;
cin >> a; // Get a string from input
int number;
try
{
number = strtoi(a, 0, 10); // Try to convert the string to an int
// Throws an exception if it cannot be converted.
}
catch(const invalid_argument&)
{
// If the number could not be converted, catch the exception, and show an error message.
cout << "Enter only Numbers" << endl;
throw;
}
cout << "The value is: " << number << endl;
return 0;
}
Upvotes: 1
Reputation: 5091
Your variable is always an integer. Even if you enter a character, it'll be given the ASCII value of the character.
Upvotes: 0