C++/checking if a string consists of all numbers or not.[Part II]
Expert: Eddie - 2/27/2005
QuestionI 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
AnswerHello 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