user1594138
user1594138

Reputation: 1011

Splitting string to 2 vectors. Trouble converting string to float type

Below I have a string called line that is coming from a file. The string has commas to separate it, where the first part goes to a string vector, and the second to a float vector. Anything after that is not used.

The first part comes out as "text", which is correct. But the second one shows "248", while it's supposed to say "1.234"

I need help converting this correctly. Any help would be greatly appreciated, thanks.

I'm very new to programming. Sorry for any horrible style.

#include <iostream>
#include <string>
#include <vector>
using namespace std;

int main ()
{
  string line ("test,1.234,4.3245,5.231");
  string comma (",");
  size_t found;
  size_t found2;
  string round1;
  float round2;
  vector<string> vector1;
  vector<float> vector2;

  // Finds locations of first 2 commas
  found = line.find(comma);
  if (found!=string::npos)

  found2 = line.find(comma,found+1);
  if (found2!=string::npos)





    //Puts data before first comma to round1 (string type)
    for (int a = 0; a < found; a++){
    round1 = round1 += line[a];
    }

    //Puts data after first comma and before second comma to round2 (float type)
    for (int b = found+1; b < found2; b++){
    round2 = round2 += line[b];
    }


    //Puts data to vectors
    vector1.push_back(round1);
    vector2.push_back(round2);


cout << vector1[0] << endl << vector2[0] << endl;


  return 0;
}

Upvotes: 2

Views: 310

Answers (2)

Borgleader
Borgleader

Reputation: 15916

Your problem is that you're adding chars to a float value, you can't convert it in this way. What you were actually doing is adding up the hex values of the characters that made up your number, if you look in an ASCII table you'll notice 1=49, .=46, 2=50, 3=51, 4=52. If you sum those 5 up you get 248. Also, even though it's wrong in this case:

round2 = round2 += line[b];

should be:

round2 += line[b];

The reason being that the += operator will is equivalent to:

round2 = round2 + line[b];

so it makes no sense to add an extra round2 = in front of it.

In order to do this properly use stringstreams like so:

#include <string>
#include <sstream>

int main()
{
    float f;
    std::stringstream floatStream;
    floatStream << "123.4";
    floatStream >> f;

    return 0;
}

Upvotes: 1

PiotrNycz
PiotrNycz

Reputation: 24402

Consider to use stringstream and getline(..., ',') :

string line;
string strPart;
string floatPart;
istringstream isline(line);
getline(isline, strPart, ',');
getline(isline, floatPart, ',');
istringstream isfloat(floatPart);
float f;
isfloat >> f;

Of course this requires a lot of checking against possible errors but should work.

Upvotes: 0

Related Questions