2016-04-12 149 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(); 
}