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?
THis will result in undefined behaviour.
anon
2009-07-28 18:05:02
+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
2009-07-28 17:57:34
@Neil, my implementation (gcc) does. I can't seem to find an official answer here. What is specified to happen?
Jesse Beder
2009-07-28 18:16:03
Standard says that the constructor parameter "shall not be a null pointer" - it doesn't specify that any exceptions are thrown.
anon
2009-07-28 18:22:15
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
2009-07-29 07:20:29
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
2009-07-29 16:59:45
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
2009-07-28 17:59:12
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
2009-07-28 18:06:40
+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
2009-07-28 17:59:21
+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
2009-07-28 18:12:06