为什么字符串不接受输入[重复]

问题描述 投票:-1回答:1

此问题已经在这里有了答案:

它没有将字符串作为输入

它使用两个整数作为输入,但不使用字符串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;
      }

    }

}



52

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

c++ string getline
1个回答
0
投票
您正在将>>运算符与getline混合在一起。您需要清除\n剩下的换行符cin >>的输入缓冲区。

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


cin >> w; cin.ignore(); // this will flush the input buffer string str; getline(cin,str);
© www.soinside.com 2019 - 2024. All rights reserved.