user3097625
user3097625

Reputation: 101

How can I output the result of atof as 1.0 instead of 1

I have a problem using atof, here is the code:

#include <stdio.h>
#include <cstdlib> 
#include <iostream>
#include <string>
using namespace std;

int main(){
    std::string num ("1.0");
    //std::string num ("1.1");
    cout<< atof(num.c_str());
    return 0;
}

If the num string is "1.1" , it can correctly cout 1.1. But if I want to keep the zero when the num string is "1.0" (want it to be 1.0 but not 1), what should I do?

Upvotes: 2

Views: 1554

Answers (2)

Shafik Yaghmour
Shafik Yaghmour

Reputation: 158469

You need to use std::fixed and std::setprecision, like so:

std::cout<< std::fixed << std::setprecision(1) << atof(num.c_str());

This will require that you include the iomanip header.

Upvotes: 2

user2485710
user2485710

Reputation: 9801

A possible solution is

#include <cstdio>
#include <iostream>
#include <string>
#include <iomanip>

int main() {
  std::cout.precision(3);
  std::cout.setf(std::ios::fixed);
  std::string s("1.0");
  float f = 0.0f;
  sscanf(s.c_str(), "%f", &f);
  // alternative way of setting this flags
  // std::cout << std::fixed << std::setprecision(3) << f << "\n";
  std::cout << f << "\n";
  return (0);
}

notice that there are at least 2 ways of accomplishing the same format for the output, I left one of them commented out .

Upvotes: 0

Related Questions