我有一個while循環和代碼下面退出一個while循環,cin。使用CTRL-Z/CTRL-d不工作C++
string namn, word;
while(getline(cin, namn)){
istringstream iss(namn);
vector<string> v;
while(iss >> word){
v.push_back(word);
}
for(auto elements: v){
cout << elements << endl;
}
}
cout << "do something" <<endl;
當我運行該代碼的循環工作正常,但使用CTRL-Z我不能退出循環(在窗)
我自己也嘗試下面這樣:
int main(){
string namn;
string pris;
string antal;
vector<string> v;
while(cin >> namn >> pris >> antal){
v.push_back(namn);
v.push_back(pris);
v.push_back(antal);
}
// do something with the vector maybe print it
// i can not exit the loop and continue here
return 0;
}
我也曾嘗試第三解決方案,但它不工作之一:
int main(){
string name;
vector<string> v;
while(!cin.eof()&& cin.good()){
cin >> name;
v.push_back(name);
}
// after exiting the loop with ctrl-Z (in windows, ctrl-d in linux)
// do something with the vector, but it never goes here
}
我正在做的或即將解決的任務是您有多行輸入,例如名稱,價格,金額。那麼我將把這些物品存儲在一個矢量中。退出應該與使用ctrl-z不打字退出或其他。
您是否在ctrl-z之後按回車鍵?嘗試添加一箇中斷,如果namn.empty()以空行退出循環。 –