-
string to integer?
After testing the user input and confirming contains only numbers, how do I convert the string to an integer. Have spent hours attempting to do so, obvoisly without success....
Or change the code below to accept an integer and test...?
#include <iostream>
#include <cstring>
#include <string>
#include <cctype>
using namespace std;
int main()
{
string answer;
char again;
do
{
cout << "Enter a number or letter ";
cin >> answer;
for (int i = 0; i < answer.length(); i++)
{
if (!isdigit(answer[i]))
{
cout << answer << " is not a number!" << endl;
break;
}
}
cout << "\nAnswer is " << answer << endl;
cout << "more> ";
cin >> again;
}while(again == 'y');
return 0;
}
-
Code:
#include <iostream>
#include <string>
#include <cctype>
#include <sstream>
using namespace std;
int main() {
cout << "Please enter an integer: " << flush;
int num;
cin >> num;
cout << endl;
if(cin.fail()) {
cout << "You didn't enter a number!" << endl;
return -1;
}
cout << "Final number: " << num << endl;
return 0;
}
:)
Similar to yours but I tweaked it for a more C++-like style ;)
Quick note - if you enter too large a number it overflows and the internal stream sets the fail bit.
-
Radix lecti :D mmm?
couch potato *** laude :D
-
One does one's best :D
PS: Just as well the server went strange earlier; saved me posting the earlier version involving the original isdigit() loop to verify the string.... :eek: *shudder*
-
parksie code
much gratitude!!!!!
Still need help with a slight tweak....
If I enter 8r33 it accepts the entry as 8.
The ultimate would be the entire entry must me numeric....however, what I have now is alot more than what I had.
If there is a simple tweak to check the entire entry, well that would make my semester!!!!!!!
-
Code:
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
int main() {
cout << "Please enter an integer: " << flush;
int num;
cin >> num;
cout << endl;
// get the rest of the stream
string s;
getline(cin, s);
if(!s.empty() || cin.fail()) {
cout << "You didn't enter a number!" << endl;
return -1;
}
cout << "Final number: " << num << endl;
return 0;
}
The getline in the middle extracts what's left on the input line, since the cin >> num has only extracted the first numeric portion it can. If it goes straight to a newline, then the string will be empty since no extra characters were present.