我想要做的是從終端獲取用戶輸入,并在我的程式的其他功能中使用這個輸入。由于我的函式僅將輸入流作為引數,因此我想將輸入字串轉換為輸入流。
int main(int argc, char** argv)
{
std::vector<std::string> args(argv, argv argc);
if(args.size() == 1){ //if no arguments are passed in the console
std::string from_console;
std::istringstream is;
std::vector<std::string> input;
while(!getline(std::cin,from_console).eof()){
input.emplace_back(from_console);
}
for(std::string str : input){
std::cout << "\n" << str;
}
}
當我嘗試這段代碼時出現的另一個問題是,當我用一堆字符而不是新行結束控制臺輸入時(按 enter 然后 ctrl d),該行被忽略并且沒有被列印出來。示例:當我輸入以下內容時:
aaa bbb
ccc ctrl d
我只得到了第一行(aaa bbb),沒有列印出 ccc。但:
aaa bbb
ccc
ctrl d
也列印出 ccc ,但它確實忽略了新行。那么為什么會這樣呢?
uj5u.com熱心網友回復:
有沒有辦法在 C 中將輸入字串轉換為輸入流?
是的,有可能。這是std::istringstream
為了什么。例子:
std::string input = some_input;
std::istringstream istream(input); // this is an input stream
uj5u.com熱心網友回復:
該類有一個以 a作為引數的建構式,它使用作為流初始內容傳遞的字串的副本std::istringstream
。std::string
因此,與其使用 astd::vector
來存盤來自控制臺的所有輸入行,不如將它們添加到一個(不同的)std::string
物件中,記住在每個物件之后添加換行符,然后從中構造你std::istringstream
的。
這是一個簡單的示例,它顯示了如何使用std::getline
(與您的函式一樣,將輸入流作為其第一個引數)同樣好地使用以及像這樣創建std::cin
的std::istringstream
物件:
#include <iostream>
#include <sstream>
int main()
{
std::string buffer; // Create an empty buffer to start with
std::string input;
// Fill buffer with input ...
do {
getline(std::cin, input);
buffer = input;
buffer = '\n';
} while (!input.empty()); // ... until we enter a blank line
// Create stringstream from buffer ...
std::istringstream iss{ buffer };
// Feed input back:
do {
getline(iss, input);
std::cout << input << "\n";
} while (!input.empty());
return 0;
}
uj5u.com熱心網友回復:
當 eof 與最后一行內容在同一行時,getline(std::cin,from_console)
將到達它并.eof()
回傳 true,因此最后一行被讀入字串from_console
但不推入向量。
有兩種方法:
- 通過手動將最后一行推入向量來修改代碼:
while(!getline(std::cin,from_console).eof()){
input.emplace_back(from_console);
}
input.emplace_back(from_console); // add one line
for(std::string str : input){
iterator
可以是一種優雅的方式:
#include <iterator>
// ...
if (args.size() == 1) { // if no arguments are passed in the console
copy(std::istream_iterator<std::string>(std::cin), {},
std::ostream_iterator<std::string>(std::cout, "\n"));
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/470097.html
上一篇:makefile中的回圈main