K
Kavya
I saw these two ways for validating input
First Way
--------------
#include <iostream>
#include <limits>
using namespace std;
int main() {
int number = 0;
cout << "Enter an integer: ";
cin >> number;
cin.ignore(numeric_limits<int>::max(), '\n');
if (!cin || cin.gcount() != 1)
cout << "Not a numeric value.";
else
cout << "Your entered number: " << number;
return 0;
}
Second Way
--------------------
#include <iostream>
using std::cout;
using std::cin;
using std::endl;
int main() {
int inum,count=0;
cout<<"Enter integers, <Return> after each, <Ctrl>Z to
finish"<<endl;
while(cin>>inum,cin.good()) {
cout<<"Number "<<++count<<":"<<inum<<endl;
}
return 0;
}
Which of them is better? I find 2nd method easier than the other. Won't
second method be sufficient?
First Way
--------------
#include <iostream>
#include <limits>
using namespace std;
int main() {
int number = 0;
cout << "Enter an integer: ";
cin >> number;
cin.ignore(numeric_limits<int>::max(), '\n');
if (!cin || cin.gcount() != 1)
cout << "Not a numeric value.";
else
cout << "Your entered number: " << number;
return 0;
}
Second Way
--------------------
#include <iostream>
using std::cout;
using std::cin;
using std::endl;
int main() {
int inum,count=0;
cout<<"Enter integers, <Return> after each, <Ctrl>Z to
finish"<<endl;
while(cin>>inum,cin.good()) {
cout<<"Number "<<++count<<":"<<inum<<endl;
}
return 0;
}
Which of them is better? I find 2nd method easier than the other. Won't
second method be sufficient?