Home  >  Q&A  >  body text

c++ - cin输入时按回车结束

vector<string> ivec;
    string str;
    while(cin >> str)
        ivec.push_back(str);

请问如何实现输入数据按回车结束,而不是crtl +z

PHP中文网PHP中文网2714 days ago541

reply all(2)I'll reply

  • PHP中文网

    PHP中文网2017-04-17 12:04:55

    This question should not determine whether str is equal to 'n' or "n", but should determine whether str is empty, that is,

    vector<string> ivec;
    string str;
    while(getline(cin, str))
      if (str.empty()) break;
      ivec.push_back(str);

    Cause: When you don’t enter any characters and just hit Enter, getline only encounters a newline character, and getline extracts and discards it, so str is empty.

    reply
    0
  • 怪我咯

    怪我咯2017-04-17 12:04:55

    while(cin>>str){
        if(str等于换行){
            break;
        }
        ivec.push_back(str);
    }

    reply
    0
  • Cancelreply