I need to use an std::string
to store data retrieved by fgets()
. To do this I need to convert the char*
return value from fgets()
into an std::string
to store in an array. How can this be done?
相关问题
- Sorting 3 numbers without branching [closed]
- How to compile C++ code in GDB?
- Why does const allow implicit conversion of refere
- thread_local variables initialization
- What uses more memory in c++? An 2 ints or 2 funct
相关文章
- Class layout in C++: Why are members sometimes ord
- How to mock methods return object with deleted cop
- Which is the best way to multiply a large and spar
- C++ default constructor does not initialize pointe
- Selecting only the first few characters in a strin
- What exactly do pointers store? (C++)
- Converting glm::lookat matrix to quaternion and ba
- What is the correct way to declare and use a FILE
Most answers talks about constructing
std::string
.If already constructed, just use assignment operator.
I would like to mention a new method which uses the user defined literal
s
. This isn't new, but it will be more common because it was added in the C++14 Standard Library.Largely superfluous in the general case:
But it allows you to use auto, also with wide strings:
And here is where it really shines:
Why using
fgets()
when you are programming C++? Why notstd::getline()
?If you already know size of the char*, use this instead
This doesn't use strlen.
EDIT: If string variable already exists, use assign():
std::string
has a constructor for this:Just make sure that your
char *
isn'tNULL
, or else the behavior is undefined.