退出while循环,cin.使用ctrl-Z/ctrl-D无法使用c++

exit a while loop , cin . using ctrl-Z/ctrl-D not working c++

本文关键字:ctrl-D c++ ctrl-Z 循环 while cin 使用 退出      更新时间:2023-10-16

我在下面有一个while循环和代码

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退出循环(在windows中)。

我也在下面尝试过:

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而不是键入quit或其他内容。

我解决了自己的问题。问题是,我以前使用istringstream,改为使用stringstream,现在退出时使用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();
}

显然,std::basic_ios::operator bool()返回流是否没有失败,它与!eof()不同。你可能不得不把你的条件改成while(cin >> namn >> pris >> antal && !cin.eof())