Float to string without trailing zeros - c++

What's the recommended way to format a float to a string without trailing zeros?
to_string() returns "1.350000" as does sprintf. I don't want a fixed amount of decimals...
#include <iostream>
#include <string>
using namespace std;
int main()
{
string s = to_string(1.35);
cout << s << endl;
}

#include <iostream>
#include <string>
#include <sstream>
using namespace std;
int main() {
stringstream ss;
ss << 1.35;
cout << ss.str();
return 0;
}

std::to_string & sprintf does not give you any power to control the number of trailing zero you get when converting a float to a string. Try using std::stringstream instead, you'll have all the options you need to control the trailing zeros.

Related

How to parse date format from std::cin into stringstream buffer in c++? [duplicate]

This question already has answers here:
Why doesn't [01-12] range work as expected?
(7 answers)
Closed 2 years ago.
Having this class:
date.hpp:
#ifndef DATE_HPP
#define DATE_HPP
#include <time.h>
#include <iostream>
#include <sstream>
class Date
{
std::stringstream format;
time_t date;
struct tm *date_tm;
public:
Date() : date(time(NULL)), date_tm(localtime(&date)) {}
Date(std::istream &in);
Date(std::string str);
const std::string getDate();
const bool dateMatch(std::string str);
};
#endif //DATE_HPP
And this ctors: date.cpp:
#include "date.hpp"
#include <iostream>
#include <sstream>
#include <iomanip>
#include <string>
#include <regex>
bool isDate(std::string target)
{
std::regex reg("[1-12]{2}/[1-31]{2}[00-99]{2}");
return std::regex_search(target, reg);
}
Date::Date(std::istream &in)
{
date_tm = new struct tm;
std::cout << "enter date [mm/dd/yy]: ";
format.basic_ios::rdbuf(in.rdbuf());
if (isDate(format.str()))
{
format >> std::get_time(date_tm, "%m/%d/%y");
}
else
{
std::cout << "Format of date is not valid\n";
}
}
...
If I try to use the ctor with std::istream argument:
#include "date.hpp"
#include <iostream>
using namespace std;
int main()
{
Date d(cin);
cout << d.getDate() << '\n';
}
Then the date format checks fails even before I can something write to cin. What is wrong now?
You're format should be "%m/%d/%Y". See: https://en.cppreference.com/w/cpp/io/manip/get_time . Also your regex is missing a '/'. Plus your regex number ranges aren't quite right; they match a character class, not a number. "[1-12]" I think matches the one-character strings "1" and "2" only. You need to do something different with number ranges. You can check if the date parsing failed by checking whether format.fail() is true instead of running a regex. Plus I am skeptical of you're method of initializing format. It'd be better, I think, to just write
std::string s;
std::getline(std::cin, s);
std::stringstream format(s);
.

how can change string to integer?

I will have to take the input as a string.Then turn it to an integer.Then use it in calculations.
#include <iostream>
#include <bits/stdc++.h>
using namespace std;
int main()
{
string word;
cin>>word;
word=stol(word);
cout<<word;
return 0;
}
do not store it in word again because you declared word at first as string
so instead create another variable of type( int/float/double) and do the "stoi(word)"
(add this to your code and remove the word=stoi(word)" )
here is full code :
#include <iostream>
#include <string>
using namespace std;
int main()
{
int x;
string word;
cin>>word;
x=stoi(word);
//now you can use x in any mathematical operation you want
//try couting the x or (add, multiply,...etc to it)
}

How to assign char to string object in c++?

i am trying to convert the string into capital letter string by assigning single char's to string like this:-
#include <iostream>
#include <string>
#include <cstring>
#include <cctype>
using namespace std;
int main()
{
string a;
getline(cin,a);
string b;
b.reserve(a.size()+1);
for(int i=(a.size()),i1=0;1;i1++)
{
if(b[i1]!='\0')
b[i1]=(char)toupper(a[i1]);
else
{
a[i1]='\0';
break;
}
}
cout << b <<endl;
}
every when run a.out by ./a.out ,Only endl gets prints
here is sample run:-
$ ./a.out
play clash royale
$
What is wrong in my program?? How can I assign single char to string??
There are some issues with your program. The main one is probably the diference between string reserve and string resize. What you want in your program is already had a string of a.size() length, so, use b.resize(a.size()).
A working version is bellow (there are better ways to write this, just being most consistent with OP proposal):
#include <iostream>
#include <string>
#include <cstring>
#include <cctype>
using namespace std;
int main()
{
string a;
getline(cin,a);
string b;
b.resize(a.size());
for(int i1=0; i1 < a.size();i1++)
{
if(a[i1]!='\0')
b[i1]=(char)toupper(a[i1]);
else
{
b[i1]='\0';
break;
}
}
cout << b <<endl;
}

Copy float to string

I want to copy the contents of a float to a string in C++. This doesn't work.
#include <iostream>
#include <sstream>
using namespace std;
int main() {
float ans = getFloat();
stringstream ss;
string strAns;
ss >> ans;
strAns = ss.str();
cout << strAns << "\n"; // displays "0"
return 0;
}
How do I do this?
I think
ss>>ans;
should be
ss<<ans;
Edit:
As James Kanze noted, you are better off using std::ostringstream instead of std::stringstream as you are not using the bidirectional functionality of the first one. This way the compiler would also throw an error that you extracting ans from the string instead of inserting it into the string.
ss << ans; instead of ss >> ans and it will work
To work with stringstreams, you have to use the PUT TO operator( << ), with an object on the right hand side. That will convert the operator to a string(if the operator is defined for the particular type)(this operator<< is already defined for a stringstream object with float object).
Then, convert the string stream to a string.. and you will have successfully converted the object to string.
As the other answers show, it should be ss << ans, since << is used for ostreams and >> is used for istreams.
If you want just to print the float to cout, you can of course avoid the detour and just write std::cout << ans;, but I guess you want to use the string otherwise.
You should however be aware of the simplifications provided by Boost's and C++11's libraries:
#include <iostream>
#include <string> //for std::string and std::to_string
#include <boost/lexical_cast.hpp>
using namesapce std;
int main() {
float ans=getFloat();
string strAns1 = boost::lexical_cast<string>(ans); //boost way
auto strAns2 = std::to_string(ans); //C++11 way
cout << "boost: " << strAns1 << "\n"
<< "C++11: " << strAns2 << "\n";
}
You are using wrong operator:
#include <iostream>
#include <sstream>
using namespace std;
int main() {
float ans=getFloat();
stringstream ss;
string strAns;
ss << ans;
strAns=ss.str();
cout<<strAns<<"\n"; // displays "0"
return 0;
}
Just one line wrong here by the look of it. You need to stream the float into the stringsteram like this:
ss << ans;
Use
strAns = std::to_string(ans);

Reading parts of an input file

I would like to read an input file in C++, for which the structure (or lack of) would be something like a series of lines with text = number, such as
input1 = 10
input2 = 4
set1 = 1.2
set2 = 1.e3
I want to get the number out of the line, and throw the rest away. Numbers can be either integers or doubles, but I know when they are one or other.
I also would like to read it such as
input1 = 10
input2=4
set1 =1.2
set2= 1.e3
so as to be more robust to the user. I think this means that it shouldn't be red in a formatted fashion.
Anyway, is there a smart way to do that?
I have already tried the following, but with minimal knowledge of what I've been doing, so the result was as expected... no success.
#include <stdio.h>
#include <stdlib.h>
#include <float.h>
#include <math.h>
#include <iostream>
#include <fstream>
#include <iomanip>
#include <cstdlib>
#include <boost/lexical_cast.hpp>
#include <string>
using namespace std;
using namespace boost;
int main(){
string tmp;
char temp[100];
int i,j,k;
ifstream InFile("input.dat");
//strtol
InFile.getline(temp,100);
k=strtol(temp,0,10);
cout << k << endl;
//lexical_cast
InFile.getline(temp,100);
j = lexical_cast<int>(temp);
cout << j << endl;
//Direct read
InFile >> tmp >> i;
cout << i << endl;
return 0;
}
Simply read one line at a time.
Then split each line on the '=' sign. Use the stream functionality do the rest.
#include <sstream>
#include <fstream>
#include <iostream>
#include <string>
int main()
{
std::ifstream data("input.dat");
std::string line;
while(std::getline(data,line))
{
std::stringstream str(line);
std::string text;
std::getline(str,text,'=');
double value;
str >> value;
}
}
With error checking:
#include <sstream>
#include <fstream>
#include <iostream>
#include <string>
int main()
{
std::ifstream data("input.dat");
std::string line;
while(std::getline(data,line))
{
std::stringstream str(line);
std::string text;
double value;
if ((std::getline(str,text,'=')) && (str >> value))
{
// Happy Days..
// Do processing.
continue; // To start next iteration of loop.
}
// If we get here. An error occurred.
// By doing nothing the line will be ignored.
// Maybe just log an error.
}
}
There are already some fine solutions here. However, just to throw it out there, some comments implied that Boost Spirit is an inappropriate solution for this problem. I'm not sure I completely disagree. However, the following solution is very terse, readable (if you know EBNF) and error-tolerant. I'd consider using it.
#include <fstream>
#include <string>
#include <boost/spirit.hpp>
using namespace std;
using namespace boost::spirit;
int main()
{
ifstream data("input.dat");
string line;
vector<double> numbers;
while(getline(data,line))
{
parse(line.c_str(),
*(+~ch_p('=') >> ch_p('=') >> real_p[push_back_a(numbers)]),
space_p);
}
}
Off the top of my head:
vector<double> vals(istream &in) {
vector<double> r;
string line;
while (getline(f, line)) {
const size_t eq = line.find('=');
if (eq != string::npos) {
istringstream ss(line.substr(eq + 1));
double d = 0;
ss >> d;
if (ss) r.push_back(d);
else throw "Line contains no value";
}
else {
throw "Line contains no =";
}
}
return r;
}
int main(int argc, char *argv[]) {
vector<double> vs = vals(ifstream(argv[1]));
}
C FTW (modified to handle doubles)
#include <stdio.h>
int
main ()
{
double num;
while (!feof (stdin))
if (1 == fscanf (stdin, "%*[^=] = %lf", &num))
printf ("%g\n", num);
return 0;
}
now that you are already using boost with lexical_cast, just parse each line with boost::split() and boost::is_any_of() into 1 2-element vector, with token_compress turned on.
the following code illustrates the parse, but skips the numeric conversion, which could be solved easily with boost lexical_cast.
#include <fstream>
#include <sstream>
#include <string>
#include <iostream>
#include <vector>
#include <boost/algorithm/string/split.hpp>
#include <boost/algorithm/string/classification.hpp>
#include <boost/foreach.hpp>
using std::string;
using std::cout;
using std::ifstream;
using std::stringstream;
using std::vector;
std::string file_to_string()
{
ifstream data("data.txt");
stringstream s;
s << data.rdbuf();
return s.str();
}
void print_parameter(vector<string>& v)
{
cout << v_para[0];
cout << "=";
cout << v_para[1];
cout << std::endl;
}
vector<string> string_to_lines(const string& s)
{
return v_lines;
}
int main()
{
vector<string> v_lines;
boost::split(v_lines, file_to_string(), boost::is_any_of("\n"), boost::token_compress_on);
vector<string> v_para;
BOOST_FOREACH(string& line, v_lines)
{
if(line.empty()) continue;
boost::split(v_para, line, boost::is_any_of(" ="), boost::token_compress_on);
// test it
print_parameter(v_para);
}
}
If you are devising this format, I would suggest adopting the INI file format.
The lightweight syntaxed INI format includes sections (allows you to have a little more structure in the format) which may or may not be desirable in your case:
I.e.
[section_1]
variable_1=value1
variable_2=999
[sectionA]
variable_A=value A
variable_B=111
The external links on this wikipedia page list a number of libraries that can be used for working with these types of files that extend/replace the basic GetPrivateProfileString functions from the Windows API and support other platforms.
Most of these would handle the space padded = sign (or at least before the = since a space after the = may be intentional/significant.
Some of these libraries might also have an option to omit [sections] if you don't want that (my own C++ class for handling INI like format files has this option).
The advantage to these libraries and/or using the Windows API GetPrivateProfileXXX functions is that your program can access specific variables
(I.e. get or set the value for variable_A from sectionA) without your program having to
write/scan/rewrite the entire file.
Here's my quickest STL solution:
#include <fstream>
#include <list>
#include <locale>
void foo()
{
std::fstream f("c:\\temp\\foo.txt", std::ios_base::in);
std::list<double> numbers;
while (!f.eof())
{
int c = f.get();
if (std::isdigit(c, std::locale::classic()) ||
c == '+' ||
c == '-' ||
c == '.')
{
f.putback(c);
double val;
f >> val;
if (f.fail()) {
f.clear(f.eof() ? std::ios_base::eofbit : std::ios_base::goodbit);
continue;
}
else
{
numbers.push_back(val);
}
}
}
}
Just tested this... it works, and doesn't require anything outside of the C++ standard library.
#include <iostream>
#include <map>
#include <string>
#include <algorithm>
#include <iterator>
#include <cctype>
#include <sstream>
using namespace std; // just because this is an example...
static void print(const pair<string, double> &p)
{
cout << p.first << " = " << p.second << "\n";
}
static double to_double(const string &s)
{
double value = 0;
istringstream is(s);
is >> value;
return value;
}
static string trim(const string &s)
{
size_t b = 0;
size_t e = s.size();
while (b < e && isspace(s[b])) ++b;
while (e > b && isspace(s[e-1])) --e;
return s.substr(b, e - b);
}
static void readINI(istream &is, map<string, double> &values)
{
string key;
string value;
while (getline(is, key, '='))
{
getline(is, value, '\n');
values.insert(make_pair(trim(key), to_double(value)));
}
}
int main()
{
map<string, double> values;
readINI(cin, values);
for_each(values.begin(), values.end(), print);
return 0;
}
EDIT: I just read the original question and noticed I'm not producing an exact answer. If you don't care about the key names, juts discard them. Also, why do you need to identify the difference between integer values and floating-point values? Is 1000 an integer or a float? What about 1e3 or 1000.0? It's easy enough to check if a given floating-point value is integral, but there is a clas of numbers that are both valid integers and valid floating-point values, and you need to get into your own parsing routines if you want to deal with that correctly.