简体   繁体   English

如何从 std::cin 读取到 istringstream

[英]How to read from std::cin to istringstream

I would like to parse date in format [mm/dd/yy]:我想以 [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?但我无法从std::cin读取到std::istringstream ,但为什么呢?

  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 .在那里我有 2 个缓冲区(cin -> istream 和 istringstream),它们提供不同的缓冲区(一个用于“字符串”,另一个用于“屏幕 - stdout”),但是为什么当它们仍然只是一个流streambuf How is even the streambuf implemented in C++?甚至streambuf是如何用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::stringstd::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::istringstream ,你可以直接做:

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

Demo演示

To substitute underlying buffer, you have to call rdbuf :要替换底层缓冲区,您必须调用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演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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