Jump to content


Check out our Community Blogs



Recent Status Updates

View All Updates

Developed by TechBiz Xccelerator
Photo
- - - - -

converting string to float

stringstream string float convertion

This topic has been archived. This means that you cannot reply to this topic.
1 reply to this topic

#1 JonElias

JonElias

    CC Addict

  • Advanced Member
  • PipPipPipPipPip
  • 201 posts

Posted 14 May 2016 - 09:12 AM

i have a string containing a number with digits. then i use the stringstream libary to convert it to float. But the output only gives be whole numbers.

 

i have a text file containing letters in this format:
letter=float number

for example:
e=2.56

 

then i make this code decode the whole thing:

#include <iostream>
#include <sstream>
#include <fstream>
#include <stdlib.h>
using namespace std;

float data[26][2];
int stringfloat(string a){
	stringstream stream;
	float b;
	stream << a;
	stream >> b;
	return b;
}
int main(){
	//get data
	ifstream reader("data.txt");
	if(!reader){return -1;}
	
	string line
	string letter;
	string convstring;
	float letterdata;
	
	while(! reader.eof()){
		getline(reader,line);
		letter = line.at(0);
		letterdata = stringfloat(convstring.assign(line, 2, line.size()-1));
		cout << letter << "		" << letterdata << "		" << convstring << endl;
	}
}

which outputs:
E               16              16,63
N               8               8.14
 

it fetches the right data but the stringfloat function fails. how can i fix it?

 


"computers are useless they only give you answers" Pablo Picasso
And yes he was alive when the first programmable computer was made

#2 AceInfinity

AceInfinity

    CC Addict

  • Senior Member
  • PipPipPipPipPip
  • 312 posts

Posted 14 May 2016 - 10:56 PM

Can you see something wrong here:
int stringfloat(string a){
	stringstream stream;
	float b;
	stream << a;
	stream >> b;
	return b;
}
Extract a float from the stream, function implicitly casts that float to an int to return it...

Microsoft MVP (2012) - .NET Programming | ®Crestron DMC-T Certified Programmer
Posted Image