簡體   English   中英

將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

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);

雖然我與@πάνταῥεῖ,要做到這一點, 正確的方法是通過將代碼放到一個函數,將參數傳遞給它同意, 可以做你問什么,使用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";
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM