|
-
March 19th, 2010, 05:43 PM
#1
String_int
Hello,
I have the following situation:
I want to check if the char in a string is the same as an int.
So lets say:
int one = 1;
string test = "1234";
for(n = 0; n<4; n++)
{
if (string[n] == one) // this always comes back negative
{
action
}
}
Do I need to convert it to an int, and if so how do I do that?
Thanks,
Niels
-
March 19th, 2010, 07:18 PM
#2
Re: String_int
The character '1' does not have the value of 1 so there is no way to do a direct comparison.
http://www.codeguru.com/forum/showth...760#cpp_string
You can have instant gratification by reading the FAQs. They will provide the tools that you need to do this particular task and there are a few different ways of doing it.
-
March 20th, 2010, 04:04 AM
#3
Re: String_int
I always used this function to convert from string to int, however if i want to convert a specific value of the string (say: string[n]), this does not work.
string test = "123";
int one = atoi(test.c_str());
cout << one << endl; // returns the integer 123
string test = "123";
int one = atoi(test[1].c_str()); // returns an compilation error C2228: left of '.c_str' must have class/struct/union
cout << one << endl;
-
March 20th, 2010, 06:45 AM
#4
Re: String_int
 Originally Posted by NielsNIO
I always used this function to convert from string to int, however if i want to convert a specific value of the string (say: string[n]), this does not work.
That is because atoi() requires a null-terminated string, not a single char.
string[n] is a single char, not a null-terminated array of char, which is what atoi() requires.
If you're using ASCII, all you need to do is subtract '0'.
Code:
#include <string>
#include <iostream>
int main()
{
std::string test = "123";
int number = test[0] - '0';
std::cout << number;
}
If you want a solution using atoi:
Code:
#include <string>
#include <iostream>
#include <cstdlib>
int main()
{
std::string test = "123";
char ch[2] = {0}; // temporary, 1-character null-terminated buffer
ch[0] = test[0];
int number = atoi(ch);
std::cout << number;
}
Code:
#include <string>
#include <iostream>
#include <cstdlib>
int main()
{
std::string test = "123";
int number = atoi((test.substr(0,1)).c_str());
std::cout << number;
}
Regards,
Paul McKenzie
-
March 20th, 2010, 07:44 AM
#5
Re: String_int
Thank you very much Paul!
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|