为什么字符串不接受输入

时间:2019-10-13 09:55:14

标签: c++ string getline

它没有将字符串作为输入

它将两个整数作为输入,而不是字符串str作为输入 而输入端子仅接受两个输入就停止了

#include <iostream>
#include <vector>
#include <string>
using namespace std;

int main(){
    int l;
    cin >> l;
    for(int i=0;i<l;i++){
      int w;
      cin >> w;
      string str;
      getline(cin,str);
      vector<int> n;
      for(int j=0;j<w;j++){
        if (str[j] == '1'){
            n.push_back(j+1);
        }
      }
      int xw = w/2;
      if (n.back() > xw){
         cout << n.back()*2 << endl;
      }else{
          cout << w << endl;
      }

    }

}



5 2

(程序退出,代码为-1073741819)

1 个答案:

答案 0 :(得分:0)

您正在将>>运算符与getline混合使用。

您需要清除输入缓冲区,\n会在其上保留换行符cin >>


请参见下面的代码段,并相应地调整代码。

  cin >> w;
  cin.ignore(); // this will flush the input buffer
  string str; 
  getline(cin,str);