2016-04-12 20 views
0

を働いていないCTRL-Z/CTRL-Dを使用して、私は、whileループとコード whileループ、cinを終了します。 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を使用してループを終了することはできません(中私はまた、第三の溶液Sを試してみました

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の後にEnterキーを押しましたか? 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(); 
}