【问题标题】:Set std:cin to a string将 std:cin 设置为字符串
【发布时间】:2016-12-14 15:08:09
【问题描述】:

为了便于测试,我希望将 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::stringstream
  • 如果你使用的是 linux/unix,在 shell 上使用| 是值得的。因此,您使用字符串创建一个文件,然后执行cat myCinFile | myProgram
  • 恕我直言,更好的更正方法是在您的函数中使用std::istream 并传递“std::stringstream”或“std::ifstream”。

标签: c++ stream cin


【解决方案1】:

IMO 的最佳解决方案是将核心代码重构为接受 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);

【讨论】:

    【解决方案2】:

    虽然我同意@πάντα ῥεῖ 的观点,即正确的方法是将代码放入函数中并将参数传递给它,但 也是可能的使用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";
    }
    

    【讨论】:

    • 谢谢。我不确定为什么这么多人在不知道我的具体用例的情况下否决了我的问题。我真的认为重定向缓冲区以进行快速测试对我来说是最好的方法。
    • @user5797668 “不知道我的具体用例。”好吧,你也许应该在你的问题中更清楚地说明你的用例。
    • 这有什么关系?
    • 我做到了,它是“为了便于测试”。
    猜你喜欢
    • 2023-03-09
    • 1970-01-01
    • 2017-11-05
    • 1970-01-01
    • 2013-06-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多