Help converting string to Char and Float

So I have to convert ("a499.9") into a char and a float while ignoring the a.

I have the string stored in a buffer and found how to get the char, 4. But I don't know how to get 99.9 as a float. Any ideas? here is my code so far.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <string>

using namespace std;


main()
{

buffer = "a499.9";
char position;
float hours;

position = buffer[1];

hours = buffer[2];

cout << position << endl << hours << endl;

return 0;

}


My output:
4
0


Anyone have any ideas how to get that double out?
Last edited on
closed account (Dy7SLyTq)
you can go the c way and use <ctypes.h> or the c++ way and use <sstream> with istringstream
Here is the new code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23

#include <string>

using namespace std;


main()
{

buffer = "a499.9";
char position;
float hours;

position = buffer[1];

hours = stof(buffer,2);

cout << position << endl << hours << endl;

return 0;

}


But it says build failed "error: 'stof' was not declared in this scope? Isn't stof part of <string>??
closed account (Dy7SLyTq)
no. its in <cstdlib> or that might be atoi thoug... why not write your own? its always good practice
I wouldn't even know where to begin to write my own... Is there no easy way to just retrieve the float like I did for the character starting from 9?
closed account (Dy7SLyTq)
yes...
<ctypes> <--- I dont recommend but its still an option
<sstream> <-- amazing
Ah! Yes sstream is the way to go thank you!
Topic archived. No new replies allowed.