謝謝您的幫助。我的程式從標準輸入讀取行。第一個有一個確定程式運行模式的單一數字,其余的包含不確定長度的數字序列。行數由模式決定。我想將這些行決議為 int 向量。為此,我使用了 getline 和 istringstream。然后我得到帶有格式化提取的數字>>。我第一次將字串傳遞給流,沒有任何問題,字串正確傳遞給流,我可以從中讀取格式化的輸入。但是,如果我得到另一條線并將其傳遞給同一個流,則會發生一些奇怪的事情。字串被正確復制到流中,我通過寫
std::cout << iss.str() << std::endl
但是,當我嘗試從行中提取數字時,卻沒有。
這是一個最小的可重現示例:
(我嘗試用兩個不同的流來做它并且它有效,問題是我在 switch 塊中有案例,所以它不允許我在其中初始化流,并且流的數量從模式到模式。)
#include <iostream>
#include <sstream>
#include <vector>
#include <string>
using namespace std;
int main()
{
string line;
int problem_type = -1, input_number = -1;
vector<int> sequence;
istringstream iss;
/* Get the problem type */
getline(cin, line);
iss.str(line);
if (!iss)
return -1;
cout << "Stream contents: " << iss.str() << endl;
iss >> problem_type;
cout << "Extracted numbers: " << problem_type << endl;
getline(cin, line);
iss.str(line);
if (!iss)
return -1;
cout << "Stream contents: " << iss.str() << endl;
cout << "Extracted numbers:";
while(iss >> input_number) {
cout << " " << input_number;
sequence.push_back(input_number);
}
cout << endl;
return 0;
}
輸入:
1
1 2 3 4 5
輸出:
Stream contents: 2
Extracted numbers: 2
Stream contents: 1 2 3 4 5
Extracted numbers:
預期輸出:
Stream contents: 2
Extracted numbers: 2
Stream contents: 1 2 3 4 5
Extracted numbers: 1 2 3 4 5
uj5u.com熱心網友回復:
一旦你閱讀iss >> problem_type;,
cout << "eof: " << iss.eof() << endl;
輸出
eof: 1
nextiss.str(line);不重置流狀態,回圈條件為假。你要
iss.clear();
while(iss >> input_number) {
cout << " " << input_number;
sequence.push_back(input_number);
}
輸出
Stream contents: 1
Extracted numbers: 1
Stream contents: 1 2 3 4 5
Extracted numbers: 1 2 3 4 5
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/386153.html
上一篇:在頭檔案中定義函式是否不當?
