Reputation: 109
Here is my question, I created char temp[100] to store the numbers in a file, the temp_i
is the index of current position(the numbers has temp_i
digits)
How to convert the char array temp from 0 to temp_i
into the value
I created?
Can any body help me?
stack<int> first;
char temp[10]={'0','0','0','0','0','0','0','0','0','0'};
int temp_i = 0;
bool isDouble = false;
for(int index = 0; index< strlen(str); index++){
if(str[index] != ' '){
temp[temp_i++] = str[index];
}
else if(str[index] == '.') {
isDouble = true;
} else {
double value = *(double*)temp;
cout<<value<<endl;
first.push(value);
}
}
Upvotes: 1
Views: 1965
Reputation: 57678
If you allocated one more slot in your array and assigned it to '\0', you could treat your character array a C style string.
The C-style string opens up a whole bunch of library routines, such as std::strtod
and std::sscanf
which can assist you.
You could also use std::istringstream
to get your double.
Upvotes: 2
Reputation: 3781
Use sstream.
#include<sstream>
#include<iostream>
using namespace std;
int main()
{
char * str = "123.4567 813.333 999.11";
stringstream converter;
converter<<str<<str<<str;
double number0;
double number1;
double number2;
converter>>number0;
cout<<number0<<endl;
converter>>number1;
cout<<number1<<endl;
converter>>number2;
cout<<number2<<endl;
cin.ignore('\n', 100000);
return 0;
}
Returns :
123.4567
813.333
999.11
Upvotes: 0
Reputation: 3781
Atof (ascii to float) does pretty much exactly what you are trying to do.
It takes a pointer to a null ended string and returns a float.
You just have to cut your main string with all your numbers into one string per number, but that should be pretty easy with something like stringstream.
Upvotes: 0