Copy float to string - c++

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);

Related

Optimize an algorithm to find multiple specific substrings of a string

I'm new to C++ coding and just started solving competitive programming problems. I want to solve the following task: https://onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=1620.
I want to find a substring of a string. The problem is that the code below is slow and I fail the submission by getting the "time limit exceeded" "error". What can I do to speed up the code?
#include <iostream>
#include <sstream>
#include <stdio.h>
#include <string.h>
using namespace std;
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
stringstream ss;
string m;
char prob[100000];
char substring[1000];
int howManyCases = 0;
int numberOfTests = 0;
cin >> numberOfTests;
cin.ignore();
while(numberOfTests--)
{
cin >> prob >> howManyCases;
while(howManyCases--)
{
cin >> substring;
if (strstr(prob,substring)) {
ss << 'y' << "\n";
}
else
{
ss << 'n' << "\n";
}
}
}
m = ss.str();
cout << m;
return 0;
}
i would make you of <algorithm> header:
std::string parent_string = "some string lala";
std::string sub_string = "lala";
auto found = parent_string.find(sub_string);
it will return iterator to where substring is. Then I wou;d use this clause:
if (found != std::string::npos) std::cout << "y\n";
else std::cout << "n\n";
If there is no limitation to the use of standard libraries, It's always a better choice to use it instead of creating your own algorithms (that may not handle some special cases you won't think of ).
Also, swap those huge ugly c-style arrays to std::string.

why is this code not giving the desired output?

#include <sstream>
#include <vector>
#include <iostream>
using namespace std;
vector<int> parseInts(string str) {
istringstream ss(str);
vector<int> integ;
int val;
while(ss){
if(ss>>val){
integ.push_back(val);
}
}
return integ;
}
vector<int> parseInts2(string str)
{
vector<int> vec;
stringstream ss(str);
char ch;
int temp;
while(ss)
{
ss>>temp>>ch; >> operator
vec.push_back(temp);
}
return vec;
}
int main() {
string str;
cin >> str;
vector<int> integers = parseInts(str);
for(int i = 0; i < integers.size(); i++) {
cout << integers[i] << "\n";
}
return 0;
}
i want to create a stream,to a string,read integers to the stream from the string and insert it in a vector and display its elements while the output is displaying nothing.what is wrong with the code?
EDIT
basically the question ask inputs in the form of integers that are separated by commas and asks us to print the integers after parsing it. i find no significant difference between the 2 functions but parseInt2 still works(while calling the function in main,of course instead of parseInt). Why?
I fear that your question will be closed by people on SO.
But let me give you the answer.
Basically everything set already in the comments. Why not in an answer? I do not know.
Before you can read something from an std::istringstream, you need to put something in it. You need to initialize it. That is usually done by using its constructor:
istringstream ss(str);
In main, you have the problem, that you read only one value from std::cin with cin >> str;. You want to use std::getline instead, which reads a complete line. And not only "something" up to the next space. So
getline(cin, str);
will help you further.
In modern C++, with keeping the std::istringstream approach, you would probably write
#include <iostream>
#include <string>
#include <vector>
#include <iterator>
#include <sstream>
int main() {
// Read a line and check, if that worked
if (std::string str; std::getline(std::cin, str)) {
// Create and initialize a std::istringstream
std::istringstream iss(str);
// Define a variable integers, use its range constructor with iterators
std::vector integers(std::istream_iterator<int>(iss), {});
// Range based for loop
for (const int& i : integers) {
std::cout << i << "\n";
}
}
return 0;
}
That will save the subfunction.
EDIT:
OK, you want to read csv and you must use ">>".
If you want to read data separated by comma from a stream, then you need to extract:
an integer value from the stream
then a comma
then a integer
then a comma
then a integer
. . .
The extractor operator, or the functionality behind it, will always extract characters from a stream and convert it to a requested type (e.g. an integer), until it reaches a space or the conversion can not be continued any longer (for example, a "," is a separator).
That is the reason, why your 2nd function works.
It is important that you alwys check the status of the extraction operation. In the below example you will see that, at the end of the string, we try to read a comma, where there is none. The extraction fails, but we do not care. We ignore it by intent. To understand the functionality better, please see.
#include <iostream>
#include <string>
#include <sstream>
#include <vector>
int main() {
// Source or test data. We put it directly into the stream;
std::istringstream ss{ "1,2,3, 4 , 5,6" };
std::vector<int> integers{};
char comma{};
int integer{};
while (ss) {
// Read integer and check, if it could be read
if (ss >> integer) {
integers.push_back(integer);
std::cout << "Read Integer " << integer << "\n";
}
else
std::cerr << "Error: Could not read integer\n";
// Now read the comma
if (ss && (ss >> comma))
std::cout << "Read Comma: " << comma << "\n";
else
std::cerr << "Error: Could not read comma\n";
}
// SHow all values
for (const int i : integers) std::cout << i << "\n";
return 0;
}
If you have questions, I am happy to answer.

How to grab values before space and after a space in c++

For a project im working i want to grab text before the space and after the space.
to find the space i use the isspace method, any ideas how to get this done
Like 0x499602D2 noted in the commments, you can use std::stringstream to read from string just as you would do with any other stream (like std::cin):
#include <sstream>
#include <iostream>
#include <string>
int main()
{
int a, b;
std::stringstream ss(std::stringstream::in | std::stringstream::out);
ss << "12 14";
ss >> a;
ss >> b;
std::cout << a << std::endl;
std::cout << b << std::endl;
return 0;
}
Nice thing about this is that if you know how to work with std::cin or any other stream, you know how to work with stringstream, so you can adapt this example for you needs.

Is it possible to "prepare" input from cin?

In his answer, specifically in the linked Ideone example, #Nawaz shows how you can change the buffer object of cout to write to something else. This made me think of utilizing that to prepare input from cin, by filling its streambuf:
#include <iostream>
#include <sstream>
using namespace std;
int main(){
streambuf *coutbuf = cout.rdbuf(cin.rdbuf());
cout << "this goes to the input stream" << endl;
string s;
cin >> s;
cout.rdbuf(coutbuf);
cout << "after cour.rdbuf : " << s;
return 0;
}
But this doesn't quite work as expected, or in other words, it fails. :| cin still expects user input, instead of reading from the provided streambuf. Is there a way to make this work?
#include <iostream>
#include <sstream>
int main()
{
std::stringstream s("32 7.4");
std::cin.rdbuf(s.rdbuf());
int i;
double d;
if (std::cin >> i >> d)
std::cout << i << ' ' << d << '\n';
}
Disregard that question, while further investigating it, I made it work. What I did was actually the other way around than planned; I provided cin a streambuf to read from instead of filling its own.
#include <iostream>
#include <sstream>
#include <string>
using namespace std;
int main(){
stringstream ss;
ss << "Here be prepared input for cin";
streambuf* cin_buf = cin.rdbuf(ss.rdbuf());
string s;
while(cin >> s){
cout << s << " ";
}
cin.rdbuf(cin_buf);
}
Though it would still be nice to see if it's possible to provide prepared input without having to change the cin streambuf directly, aka writing to its buffer directly instead of having it read from a different one.

String in scientific notation C++ to double conversion

I've got a database filled up with doubles like the following one:
1.60000000000000000000000000000000000e+01
Does anybody know how to convert a number like that to a double in C++?
Is there a "standard" way to do this type of things? Or do I have to roll my own function?
Right now I'm doing sth like this:
#include <string>
#include <sstream>
int main() {
std::string s("1.60000000000000000000000000000000000e+01");
std::istringstream iss(s);
double d;
iss >> d;
d += 10.303030;
std::cout << d << std::endl;
}
Thanks!
Something like this? This would be the "C++" way of doing it...
#include <sstream>
using namespace std;
// ...
string s = "1.60000000000000000000000000000000000e+01";
istringstream os(s);
double d;
os >> d;
cout << d << endl;
Prints 16.
You want the standard c function atof ([A]SCII to [F]loat, but it actually uses doubles rather than floats).