Getline keeps on getting newline character. How can I avoid this?

前端 未结 6 1714
离开以前
离开以前 2020-12-14 23:56

Basically I first takes an integer as input and then test case follows. My each test case is an string. I am suppose to print the string back if the starting patten of strin

6条回答
  •  渐次进展
    2020-12-15 00:37

    you just need to accept the fact that getline will give you '\n' at the end. One solution is remove '\n' after getting it. Another solution is do not write the additional 'endl'. for example, for your problem, you can use this code

    int N;
    cin >> N;
    string line;
    getline(cin, line); // skip the first new line after N.
    for (int i = 0; i < N; i++) {
      string line;
      getline(cin, line);
      string first4 = line.substr(0, 4);
      // convert to upper case.
      std::transform(first4.begin(), first4.end(), first4.begin(), std::ptr_fun(std::toupper)); // see http://en.cppreference.com/w/cpp/algorithm/transform
      if (first4 == "HI A") {
        cout << line;  // do not include "<< endl"
      }
    }
    

提交回复
热议问题