2016-04-12 148 views
0

我有一個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不打字退出或其他。

+0

您是否在ctrl-z之後按回車鍵?嘗試添加一箇中斷,如果namn.empty()以空行退出循環。 –

回答

0

顯然,std::basic_ios::operator bool()返回流是否失敗,與!eof()不一樣。您可能必須將您的狀況更改爲while(cin >> namn >> pris >> antal && !cin.eof())

+0

嗯,我試過表達沒有運氣,還有什麼建議? – Jim

0

我解決了我自己的問題,代碼中包含更多關於我正在做的任務的代碼,但是代碼如下。 問題是我之前使用istringstream,並將它切換到stringstream istead,現在用ctrl-z/ctrl-d工作退出。 :

Firstclass myclass; 
string item, data; 
vector<string> split_input; 

// reads in on line of string until ctrl-z/ctrl-d 
while(getline(cin, data)){ 
    stringstream str_stream(data); 
    // reading the values separate adding them to vector 
    while(str_stream >> item{ 
     split_input.push_back(item); 
    } 
    // if amount is not given 
    if(v.size() == 2){ 
     myclass.insert_data(split_input[0], stod(split_input[1]), 1.00); 
    } 
    // if if amount is given 
    else{ 
     myclass.insert_data(split_input[0], stod(split_input[1]), stod(split_input[2])); 
    } 
    // clearing the vector 
    split_input.clear(); 
}