views:

2936

answers:

5

I need to use std::string to store data retrieved by fgets(). To do this I need to convert fgets() char* output into an std::string to store in an array. How can this be done?

A: 
char* data;
std::string myString(data);
Daniel A. White
THis will result in undefined behaviour.
anon
+19  A: 

std::string has a constructor for this:

const char *s = "Hello, World!";
std::string str(s);

Just make sure that your char * isn't NULL, or else the behavior is undefined.

Jesse Beder
what will happen if it is?
Carson Myers
@Jesse What is your basis for saying such an exception is thrown?
anon
@Neil, my implementation (gcc) does. I can't seem to find an official answer here. What is specified to happen?
Jesse Beder
Undefined behaviour, or so I have always believed. I'll look it up.
anon
Standard says that the constructor parameter "shall not be a null pointer" - it doesn't specify that any exceptions are thrown.
anon
Thanks. Edited...
Jesse Beder
Just to be picky, the behaviour (as pointed out by Neil) is "undefined" not "unspecified". There is a difference. The library doesn't say what happens if the pointer is null and so the behaviour is undefined.
Richard Corden
Hmmm... I always thought that since it wasn't in the specification, it was unspecified. But it appears (google indicates) that that's the definition of undefined. This strikes me as silly, but I changed it anyways.
Jesse Beder
A: 

Pass it in through the constructur:

const char* dat = "my string!";
std::string my_string( dat );

You can use the function string.c_str() to go the other way:

std::string my_string("testing!");
const char* dat = my_string.c_str();
James Thompson
`c_str()` returns `const char*`
Steve Jessop
right, you can't (shouldn't) modify the data in a std::string via c_str(). If you intend to change the data, then the c string from c_str() should be memcpy'd
Carson Myers
+2  A: 

If you already know size of the char*, use this instead

char* data = ...;
int size = ...;
std::string myString(data, size);

This doesn't use strlen.

Eugene
+5  A: 

I need to use std::string to store data retrieved by fgets().

Why using fgets() when you are programming C++? Why not std::getline()?

Paul