将cin重定向到字符串 [英] Redirect cin to a string

查看:353
本文介绍了将cin重定向到字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从字符串中输入cin。

I want to have cin read input from a string.

有办法吗?

这样的:

const char * s = "123 ab";
cin.readFrom(s);//<---- I want something like this

int i;
cin>>i;

cout<<i; //123


推荐答案

像这样:

#include <sstream>
#include <iostream>

std::istringstream stream("Some string 123");
streambuf* cin_backup = std::cin.rdbuf(stream.rdbuf());

您可能想备份std :: cin的原始rdbuf,如果要使用

You might want to back up the original rdbuf of std::cin, if you want to use it again.

这篇关于将cin重定向到字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆