简体   繁体   中英

How to read from std::cin to istringstream

I would like to parse date in format [mm/dd/yy]:

#include <sstream>
#include <iomanip>
#include <iostream>
#include <time.h>

int main()
{
    struct tm time;
    std::istringstream ss;
    std::cout << "enter string [mm/dd/yy/]: ";
    std::cin >> ss;
    ss >> std::get_time(&time, "%D");
    std::cout << time.tm_wday << std::endl;
}

But I cannot read from std::cin to std::istringstream , but why?

  1. I am also seeking for explanation about the buffers. There I have 2 buffers (cin -> istream, and istringstream), which provide different buffer (one for "string", the other for "screen - stdout"), but why the two cannot interact one another, when they are still just a streambuf . How is even the streambuf implemented in C++? Is it an array? a struct?, Could I find the source implementation of it somewhere?

You could use std::string and std::getline :

std::string input_text;
std::getline(std::cin, input_text);
std::istringstream input_text_stream(input_text);

No need of intermediate std::istringstream , you might do directly:

std::cin >> std::get_time(&time, "%D");

Demo

To substitute underlying buffer, you have to call rdbuf :

std::istringstream ss;
std::cout << "enter string [mm/dd/yy/]: ";
ss.basic_ios::rdbuf(std::cin.rdbuf()); // substitute internal ss buffer with std::cin one
ss >> std::get_time(&time, "%D");

Demo

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM