How to judge the return value of aoti()?

If the input parameter is invalid,the atoi is return 0.But when i input "0",it's return 0 too.So,I want to know How to judge that input parameter is invalid or "0" when return value is 0.
1
2
3
4
5
6
7
8
9
#include <iostream>
using namespace std;
int main()
{
	int res1,res2;
	res1 = atoi("fsfsdfs");
	res2 = atoi("0");
	cout << res1 << " " << res2 << endl;
}


ps:My English is not so well,expect my expression is clearly.
Parses the C-string str interpreting its content as an integral number, which is returned as a value of type int.

The function first discards as many whitespace characters (as in isspace) as necessary until the first non-whitespace character is found. Then, starting from this character, takes an optional initial plus or minus sign followed by as many base-10 digits as possible, and interprets them as a numerical value.

The string can contain additional characters after those that form the integral number, which are ignored and have no effect on the behavior of this function.

If the first sequence of non-whitespace characters in str is not a valid integral number, or if no such sequence exists because either str is empty or it contains only whitespace characters, no conversion is performed and zero is returned.



Just check if the c-string is "0" if so then it is 0 otherwise it is invalid. Or check if there are any non-digits if so invalid.
Last edited on
You can write a function that acts as an in-between. It will first validate the string you give it and return true if it can be converted to integer or false otherwise.

Alternatively, you can decide to use stoi function in string library (c++11), but this one throws an exception if the argument is invalid. But as long as you remember to catch std::invalid_argument exception, or std::out_of_range exception, then you are good to go.

http://www.cplusplus.com/reference/string/stoi/

Example usage here:
http://coliru.stacked-crooked.com/a/ac59b47176717a44
to giblit:

I can understand your meanning.But if input "000",the function of aoti is return value is 0 too.So,according as your advice,I can just check if there are any non-digits.
Topic archived. No new replies allowed.