Convert some variables in a vector from string to float or double

I have a vector of a class holding codons, amino acids, names, and molar masses.
Molar mass is type string right now but I need to change it to type float or double so I can add up all the values.
All the variables that are in the vector were read in from a file.

 
  vector<AminoAcid>chart;


Hope someone can help me.
Not sure what you're trying to show with the vector there, but if you want to convert a string literal or std::string into a double, I would suggest using std::stringstream.

1
2
3
4
5
6
7
8
9
10
11
12
#include <string>
#include <sstream> // std::stringstream
#include <iostream>
int main()
{
    std::string my_str("4.002602");
    std::stringstream ss(my_str);
    double n;
    ss >> n;
    std::cout << "n = " << n;
    return 0;
}

Feel free to ask more if you need help applying that to your AminoAcid class.
Last edited on
Thanks, I wanted to show how my vector took in the variables to make better sense of the problem. So I need the molar masses to become a vector. So I should use std::stringstream?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
vector<AminoAcid>chart;
string fullname, threeLetter_name, codons, molarMass
    fin.open (argv[1]);
    if(fin.fail()){
                  cout <<"error.\n";
    }
    else{
        while (!fin.eof()){
             fin>>fullname;
             fin>>threeLetter_name;
             fin>>molarMass;
             fin>>codons;
             AminoAcid tempC(fullname,threeLetter_name, molarMass, codons);//call to constructor
           chart.push_back(tempC);
        }
 fin.close();
}
Last edited on
Yes, so in your case you could do something like this, if I'm understanding correctly:

1
2
3
4
5
6
7
8
9
10
11
/// in loop:
fin >> fullname;
fin >> threeLetter_name;
fin >> molarMass;
fin >> codons;

double molarMass_num;
// stores the string as a number into molarMass_num:
std::stringstream(molarMass) >> molarMass_num; 

AminoAcid tempC(fullname,threeLetter_name, molarMass_num, codons);


Note using stringstream requires the header <sstream>

However, you don't do anything else with molarMass, why not just stream it from the file as a double to begin with?
1
2
double molarMass;
fin >> molarMass;
Last edited on
Topic archived. No new replies allowed.