converting char* to int

Hi, when trying to convert this:
char* buffer = "asddddddddddd 500 what";
to int it gives "0"
heres my code:
1
2
3
4
5
6
7
8
9
10
#include <iostream>
#include <cstdlib>

int main()
{
	char* buffer = "asddddddddddd 500 what";
	int i = atoi(buffer);
	std::cout << i << std::endl;
	return 0;
}

wats wrong?
http://www.cplusplus.com/reference/clibrary/cstdlib/atoi/

atoi() stops at the first non-whitespace character (in this case, 'a') and tries to convert it to a number. This doesn't work, so it returns 0.
So, what should i use?
Use this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
using namespace std;

int main()
{
    string msg = "abc defg 500 asdf 1234qq 7";
    stringstream buffer(msg);
    vector<int> numbers;
    
    while (true)
    {
        int n;
        buffer>>n;
        
        if (!buffer)
        {
            if (buffer.eof()) break;
            
            buffer.clear();
            string temp;
            buffer>>temp;
        }
        else numbers.push_back(n);
    }
    
    for (int i=0; i<numbers.size(); i++)
        cout << numbers[i] << ' ';
    cout << endl;
    
    return 0;
}
Last edited on
Thanks
Topic archived. No new replies allowed.