Search code examples
c++mathatoi

Converting string to float with atof() in C++


I'm new to C++ and I need help converting my string variable into a number. I need to print the person's age and her next year age on the screen but I can't figure out how. I can't use the string to do math. So can you please shoot me a couple examples please?

I tried to do it this way:

  //converts F to C
  ctemp=(ftemp-32)*5.0/9.0;

  //calculates age
  age2 = age + 1 ; age2 = atof (age2.c_str()); age = atof (age.c_str());


  cout<<name<<" is "<<age<<" now, and will be " <<age2<<" a year from now.\n"<<"Its "<<ftemp<<" in "<<city<<"--- That's "<<setprecision(2)<<ctemp<<" degrees C"<<endl;

Edit:

int main() { 
    int city; 
    double ftemp, ctemp,age,age2;
    string buf,name; //Ask user to enter age, name, temperature and city 
    cout<<"Enter your age\n"; 
    cin>>buf; 
    age = atof(buf.c_str()); 
    cout<<"Enter your full name please\n"; 
    getline(cin,name); 
    cout<<"Enter the outside temperature please\n"; 
    cin>>buf; 
    ftemp=atof(buf.c_str()); 
    cout<<"Enter the current city you are in\n"; 
    cin>>buf; 
    city=atoi(buf.c_str());
}

Solution

  • You can use stringstreams to convert the string to the data type you want:

    #include <sstream>
    #include <string>
    #include <iostream>
    
    int main() {
      std::string num_str = "10.5";
    
      std::istringstream iss(num_str);
    
      float f_val = 0;
    
      iss >> f_val;
    
      //this will output 10.5 (as expected)
      std::cout << f_val << std::endl;
    
      return 0;
    }
    

    Which will assign f_val to the value of the string.

    This approach is preferred in that it has built-in checking of conversion, and it can work on any of the fundamental C++ types. Hence, if you can can create a template function to perform the checking for you and return that particular value of the type you desire:

    #include <sstream>
    #include <iostream>
    #include <string>
    #include <stdexcept>
    
    template<typename T>
    T ConvertStringToNumber(const std::string& str)  
    {  
      std::istringstream ss(str);  
      T number = 0;  
    
      ss >> number;  
    
      if (ss.fail( )) 
      {
        throw std::invalid_argument("ConvertStringToNumber:" + str);
      }
    
       return number;  
    }
    
    int main(int argc, char argv[]){
      std::string num_str = "10.5";
      float f = ConvertStringToNumber<float>(num_str);
    
      std::cout << f << std::endl;
    
      return 0;
    }