Assign a integer to char pointer using stringstream - c++

I want to assign integer to a char pointer using stringstream. But I am getting error while running this program at line ss >> p. Please help me here i want integer to go into the buffer first and the it must be assigned to a char*.
#include <string> // std::string
#include <iostream> // std::cout
#include <sstream> // std::stringstream
using namespace std;
int main ()
{
stringstream ss;
int n=100;
char *p;
ss << n;
ss >> p; //not working
cout << ss;
return 0;
}

Use stringstream::str to get a C++ string, then use .c_str() on the string:
#include <string> // std::string
#include <iostream> // std::cout
#include <sstream> // std::stringstream
using namespace std;
int main ()
{
stringstream ss;
int n = 100;
char* p;
ss << n;
string tmp = ss.str();
p = const_cast<char*>(tmp.c_str());
cout << "p: " << p << '\n';
return 0;
}
Beware that the char pointer becomes invalid as soon as the string goes out of scope. If you need some kind of factory function behavior, return a string by value, use strlcpy or maybe new and shared_ptr.

#include <string> // std::string
#include <iostream> // std::cout
#include <sstream> // std::stringstream
using namespace std;
int main ()
{
stringstream ss;
int n=100;
char buffer[100];
char *p = buffer;
ss << n;
ss >> p;
cout << p;
return 0;
}
This is fixing only the problem you directly encountered - there's no storage behind p so it will crash. Stylistically there are many other things to improve / fix, but this should show you what part of this was actually wrong.

Related

Store cout output into variable

How can I store the output from cout into a variable of string or character type?
I have written following code but it doesn't work:
#include<iostream>
#include<stdio.h>
using namespace std;
int main(){
string n;
n = (cout<<"\nHello world");
cout<<n;
return 0;
}
#include <sstream>
std::ostringstream a;
a << "Hello, world!";
std::string b = a.str(); // Or better, `std::move(a).str()`.
std::cout << b;
Other answers have shown you how to capture formatted output using a std::(o)stringstream object directly. But, if for some reason, you really need to capture the output of std::cout, then you can temporarily redirect std::cout to use a std::ostringstream's buffer, eg:
#include <iostream>
#include <sstream>
using namespace std;
int main(){
ostringstream oss;
auto cout_buff = cout.rdbuf(oss.rdbuf());
cout << "\nHello world";
cout.rdbuf(cout_buff);
string n = oss.str();
cout << n;
return 0;
}
Online Demo
Of course there's a way! But you have to use a different kind of stream:
std::ostringstream ss;
ss << "\nHello world";
std::string result = ss.str();
Also, in C++20, you can simply use std::format:
std::string n = std::format("Hello {}! I have {} cats\n", "world", 3);
// n == "Hello world! I have 3 cats\n"

istringstream-function string_to_int cannot take c-str, why?

I learned a helper function that can convert strings to integers:
int string_to_int(string s)
{
istringstream instr(s);
int n;
instr>>n;
return n;
}
It's mentioned that the argument s cannot be c-str string, why is this the case?
But you can pass a C style string.
The reason for that is because the std::string constructor can implicitly accept a CharT* (Char type, which is char in this case) as a parameter. Thus, something like the following would work:
#include <iostream>
#include <sstream>
using namespace std;
int string_to_int(string s)
{
istringstream instr(s);
int n;
instr>>n;
return n;
}
int main()
{
const char* test = "12345";
std::cout << string_to_int(test) << "\n"; // Outputs 12345
std::cout << string_to_int("122") << "\n"; // Outputs 122
}

Cannot push C style strings into std::vector

I'm trying to push some const char* into a vector, but the vector remains unpopulated after performing the operations I would presume to fill it.
Here's my attempt, where dict is my command-line argument.
test.cc
#include <iostream>
#include <string>
#include <vector>
#include <fstream>
using namespace std;
int main(int argc, char **argv)
{
ifstream dict;
size_t dict_size;
dict.open(argv[1]); // Dictionary
vector<const char*> dictionary;
string line;
getline(dict, line);
while(!dict.fail()) {
dictionary.push_back(line.c_str());
getline(dict, line);
}
dict_size = dictionary.size();
for(int i = 0; i < dict_size; i++)
cout << "dictionary[" << i << "] is " << dictionary[i] << endl;
}
dict
Hello
World
Foo
Bar
After compiling this, I get the following output:
dictionary[0] is
dictionary[1] is
dictionary[2] is
dictionary[3] is
However, if I change the dictionary's type to vector and push back line instead of line.c_str(), I get the expected output:
dictionary[0] is Hello
dictionary[1] is World
dictionary[2] is Foo
dictionary[3] is Bar
I'm not terribly familiar with C style strings, so maybe it has something to do with null termination?
You are storing dangling pointers.
std::string::c_str() isn't a pointer to some permanent copy of data — just think, that would be leaked!
Store the std::strings instead.
Your code invokes undefined behavior, because after you do
dictionary.push_back(line.c_str());
On the next line that pointer may get deleted:
getline(dict, line); // line now is a different string
You are pushing into the dictionary pointers that point to the same address and at the last iteration it fills the memory area with an empty string. If you don't care about memory leakage you can try like this:
#include <iostream>
#include <string>
#include <vector>
#include <fstream>
using namespace std;
int main(int argc, char **argv)
{
ifstream dict;
size_t dict_size;
dict.open(argv[1]); // Dictionary
vector<char *> dictionary;
while(!dict.fail()) {
string * line = new string();
getline(dict, *line);
if(line->length()>0)
{
dictionary.push_back((char *)line->c_str());
}
}
dict_size = dictionary.size();
for(int i = 0; i < dict_size; i++)
cout << "dictionary[" << i << "] is " << dictionary[i] << endl;
}

Converting char to int c++

I'm loosing my mind at the moment and below is what I'm trying to do.
char* buffer;
sprintf(buffer, "0x%08x", 5);
*(int *)(0x834AF2AC + 0x1a) = ?buffer?;
Buffer = 0x05000000
I need to set that in memory, if I just set 05 it will set 0x00000005
Question asked better.
How can I convert an INT into a format of "0x%08x"
So 5 becomes 0x05000000
ANSWERD:
The correct answer is *(int *)(0x834AF2AC + 0x1a) = 5<<24;
Something like this:
#include <iostream> // for std::cout, std::endl
#include <string> // for std::string, std::stoi
int main()
{
std::string s{"0x05"};
int i = std::stoi(s, nullptr, 16); // convert base 16 number in s to int
std::cout << i << std::endl;
}
Two result from google which points to stackoverflow (result 1 and 2).
Convert char to int in C and C++
C char* to int conversion
I'm not sure if I understand correctly but if you want to convert an entire string to int, then I would suggest stringstream.
http://www.cplusplus.com/reference/sstream/stringstream/stringstream/
For hexadecimal string:
#include <string> // std::string
#include <iostream> // std::cout
#include <sstream> // std::stringstream
int main () {
std::stringstream ss;
ss << std::hex << 0x05;
int foo;
ss >> foo;
std::cout << "foo: " << foo << '\n';
return 0;
}

How to write a series of float from text using fstream

Example ABC.txt
10.f 30.2f 20.f
I want to retrieve those information and store inside my array. However i am unsure how to do it.
I dont understand what is
Then (if good), it calls num_get::get (using the stream's selected locale) to perform both the extraction and the parsing operations, adjusting the stream's internal state flags accordingly. Finally, it destroys the sentry object before returning.
std::fstream filestr("ABC.txt", std::fstream::in);
if(!filestr.good()) //Logical error on i/o operation
{
//Unable to process
filestr.close();
return;
}
unsigned index= 0;
unsigned count= 0;
while(filestr.good())
{
float buffer= 0.f;
filestr >> std::skipws >> buffer;
score[index]= buffer;
++index;
}
filestr.close();
There are a number of ways to do this. One way is using stringstreams, in combination with vectors and strings:
#include <fstream>
#include <iostream>
#include <string>
#include <cstdlib>
#include <sstream>
#include <vector>
using namespace std;
int main() {
std::ifstream filestr("C:\\nums.txt", std::fstream::in);
std::vector<double> numbers;
if (!(filestr.good())) {
std::cout << "BAD FILE" << std::endl;
exit(0);
}
else {
std::string temp;
double d = 0.0;
while(std::getline(filestr, temp)) {
std::istringstream iss(temp);
while(std::getline(iss, temp, ' ')) {
std::istringstream ist(temp);
ist >> f;
numbers.push_back(f);
}
}
}
//see that the vector has information in it
for (int i = 0; i < numbers.size(); i++) {
std::cout << numbers[i] << std::endl;
}
filestr.close();
return 0;
}
One thing to note is that you could also use iterators here, but that's something you could implement for yourself.
Super simple with istream_iterator. There is only one tricky bit in the code below. The vector constructor call needs an extra set of parens around the first argument to avoid the Most Vexing Parse.
#include <fstream>
#include <iostream>
#include <iterator>
#include <vector>
#include <algorithm>
using namespace std;
int
main (int argc, char** argv)
{
for (int i = 1; i < argc; ++i) {
ifstream in (argv[i]);
if (!in) {
cerr << "Failed to open " << argv[i] << endl;
continue;
}
vector<double> nums ((istream_iterator<double> (in)), istream_iterator<double> ());
copy (nums.begin (), nums.end (), ostream_iterator<double> (cout, "\n"));
}
return 0;
}