c++ 重定向 cin 输入

c语言
Article Directory

c++ 重定向 cin 输入

在一些刷题的程序测试中,需要手动输入进行测试,不太方便,多余花费时间,当然,你可以每次输入时都指定输入流,但是就太不方便了,如果,更改 cin 的输入流就变会得很方便。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <sstream>
using namespace std;
int main(){
stringstream ipt;
ipt << "hello aja";
// or
// ipt.str("hello aja");
streambuf *pbuf = ipt.rdbuf();
cin.rdbuf(pbuf);

string a, b;
cin >> a >> b;
cout << a << b;
return 0;
}

运行结果:

1
helloaja

当然,如果此时,你使用了 c 输入函数,例如 get ,scanf ,那么就不起作用了。除非,更改 std 输入流。在网上查询时,有绑定文件输入的教程,但是,这并不是我们想要的。

研究少顷,还是没什么好办法,看来还是只能用 unget 或者 putback() 了,不过一次只能 putback 一个字符,而且有缓冲区满,字符被丢弃的风险。而且,似乎,这种方法只对 scanf get 等 c 输入函数有效 所以,对于混写有些无力。目前我也没什么好方法。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <sstream>
using namespace std;
int main(){
string ipt = "hello aja";
for (int i = ipt.length() - 1; i >=0 ; i--){
ungetc(c, stdin);
}

char a[10];
string a;
scanf("%s\n", a);
printf("%s\n", s);
return 0;
}

Author: 哒琳

Permalink: http://blog.jieis.cn/2022/12b0e3b2-43d0-48a3-9e6f-64d65dd15236.html

Comments