You are here:

C++/checking if a string consists of all numbers or not.[Part II]

Advertisement


Question
I keep getting the following error message on the code

#include <string.h>
#include <iostream.h>

int main(){


char str[] = "12345";

for(int i = 0; i < strlen(str) - 1; i++) {
for(int j = 0; j <= 9; j++) {
if(atoi(str[i]) == j) {
cout << "yes!";
}
}
}

return 0;
}


and the error message is
Could not find a match for 'stoi(char)' in function main()

and i am using a borland5.5 compiler.  please help me out.
-------------------------
Followup To
Question -
Hello Eddie,

last time you have given me the code

int main(){


char str[] = "12345";
//would this work?
//string str = "12345";

for(int i = 0; i < strlen(str) - 1; i++) {
for(int j = 0; j <= 9; j++) {
if(atoi(str[i]) == j) {
cout << "yes!";
}
}
}

return 0;
}

something like this, but I do not know the appropriate include files for atoi,

and another thing is, I want to check if a string consists of all numbers.... I don't know if a char array would still be fine.

Answer -
Hello James, thank you for the question.

For atoi, the include file is <string.h>. And yes, a char array is fine for that algorithm. So is a char pointer. The only other way you can store a string that those to is a std::string. In that case, you would use the method string::c_str() to retrieve the C style string of that object.

I hope this information was helpful.

- Eddie

Answer
Hello James, thank you for the question.

I'm not sure why I didn't catch this earlier, probably because I was on my way out the door when I answered.

atoi takes in a char* as a parameter. You are passing an individual character. That's why it's complaining about ot finding a match, it thinks the atoi function has been overloaded to accept a char. Instead, pass the address of str[i](atoi(&str[i])), since the address is a pointer, and you should be good to go.

I hope this information was helpful.

- Eddie  

C++

All Answers


Answers by Expert:


Ask Experts

Volunteer


Eddie

Expertise

I can answer questions about the C++ language, object oriented design and architecture. I am knowledgable in a lot of the math that goes into programming, and am certified by ExpertRating.com. I also know a good deal about graphics via OpenGL, and GUIs.

Experience

I have completed numerous games and demos created with the C++ programming language. Currently employed as a software engineer in the modeling and simulation field. I have about 7 years experience.

©2012 About.com, a part of The New York Times Company. All rights reserved.