-2

This is the part of a code code:

time_t now = time(0);
char* date_and_time = ctime(&now);
cout << date_and_time << endl;
string date_and_time_string;
stringstream ss;
ss << noskipws << date_and_time;
ss >> noskipws >> date_and_time_string;
cout << date_and_time_string << endl;

I cant understand how date_and_time is a char when it has multiple characters, and when I want to get it to a string, it just stops when spaces come. I tried putting it with or without noskipws but to no avail. If printing date_and_time is something like "Thu Jul 01 23:52:46 2021", when it turns to string it is just "Thu".

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
  • `std::ctime` - __Return value__ - _"Pointer to a static null-terminated character string..."_ - https://en.cppreference.com/w/cpp/chrono/c/ctime . To get it into a string `std::string date_and_time_string{date_and_time};` – Richard Critten Jul 01 '21 at 22:06
  • *"I cant understand how date_and_time is a char"* -- that's good, as `char*` is not `char`. – JaMiT Jul 01 '21 at 22:15
  • First point of clarification, from [cppreference.com](https://en.cppreference.com/w/cpp/io/manip/skipws), about `noskipws`: *"Has no effect on output."*. That is, you'll see a difference if you look at `ss.str()` instead of `date_and_time_string`. Now your question should become something ("why did the stream extraction stop at a space?") for which we have a duplicate lying around somewhere. – JaMiT Jul 01 '21 at 22:21
  • Does this answer your question? [std::cin input with spaces?](https://stackoverflow.com/questions/5838711/stdcin-input-with-spaces) – JaMiT Jul 01 '21 at 22:25

1 Answers1

0

I cant understand how date_and_time is a char when it has multiple characters

It is not a single char, it is a char* pointer to a null-terminated array of chars.

when I want to get it to a string, it just stops when spaces come.

Because that is how operator>> works. It stops reading on whitespace or EOF, whichever occurs first.

I tried putting it with or without noskipws but to no avail.

noskipws before the first >> tells it not to skip leading whitespace. But your input string does not have any, so the noskipws is effectively a no-op in this situation. And it has no effect on the 2nd >> because the 1st one clears that flag from the stream after it is done reading.

If printing date_and_time is something like "Thu Jul 01 23:52:46 2021", when it turns to string it is just "Thu".

Because you are using >> to parse the string. This is normal behavior.

If you want the whole string, use std::getline() instead:

stringstream ss;
ss << date_and_time;
/* alternatively:
istringstream ss(date_and_time);
*/
getline(ss, date_and_time_string);

Or, since there is really no reason to use std::(i)stringstream at all in this situation, you can just assign date_and_time as-is directly to date_and_time_string:

date_and_time_string = date_and_time;
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770