将std:cin设置为字符串
Set std:cin to a string
为了便于测试,我希望将Cin的输入设置为可以硬编码的字符串。
例如,std::cin("test1 ntest2 n");
std::string str1;
std::string str2;
getline(cin,str1);
getline(cin,str2);
std::cout << str1 << " -> " << str2 << endl;
将读出:
test1 -> test2
在我看来,最好的解决方案是将核心代码重构为一个接受std::istream
引用的函数:
void work_with_input(std::istream& is) {
std::string str1;
std::string str2;
getline(is,str1);
getline(is,str2);
std::cout << str1 << " -> " << str2 << endl;
}
和调用测试,如:
std::istringstream iss("test1 ntest2 n");
work_with_input(iss);
和生产:
work_with_input(cin);
虽然我同意@π α ντα ρ ε ε ε的正确的方法是通过将代码放入函数并传递参数给它,但也可以使用rdbuf()
来做您所要求的事情,就像这样:
#include <iostream>
#include <sstream>
int main() {
std::istringstream in("test1 ntest2 n");
// the "trick": tell `cin` to use `in`'s buffer:
std::cin.rdbuf(in.rdbuf());
// Now read from there:
std::string str1;
std::string str2;
std::getline(std::cin, str1);
std::getline(std::cin, str2);
std::cout << str1 << " -> " << str2 << "n";
}
相关文章:
- C++ 命名参数习惯用语 - 未设置字符串属性
- 如何将字符串属性设置为 QTreeWidgetItem?
- 我如何处理有关输入的字符串大小超过字符数组设置大小的错误?
- C++如何将字符串数组中的一个点设置为枚举变量
- 从C++为字符串函数设置_ENV
- 在给定字符串上使用 tolower() 和 isalpha() 并将其输出设置为另一个字符串
- 通过比较字符设置字符串时出现问题
- 如何在 c++ 中从字符串向量设置类对象
- STD ::设置带有字符串键和潜在效率损失
- 如何调用 GetAltMonthNames 来填充外部区域设置月份字符串的安全数组
- 设置可变值通过字符串引用它
- 仅使用 getName 在主函数中设置字符串名称
- 如何将变量名设置为字符串?C++
- 在类中设置Arduino字符串值
- 如何在C++中有条件地设置 C 样式字符串?
- 在字符串列表中查找字符串,然后将字符串设置为找到的字符串?
- 从函数参数常量字符串 (&) 设置值
- 在定义过程中将std::string设置为0与将std::字符串设置为0相比
- 将字符串设置为日期格式
- 如何将包含空格的字符串设置为HTML文本字段(在表单中)的默认值