【问题标题】:getline() in C++ [duplicate]C ++中的getline()
【发布时间】:2020-01-09 10:55:36
【问题描述】:

为什么 getline 函数不在这里接受输入?

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

int main() {
    unsigned n {}, m {};
    cin >> n >> m;

    string set;
    getline(cin, set);
    cout<<set<<endl;
    return 0;
}

提供的输入:

1 5
Hello World

显示的输出:


【问题讨论】:

标签: c++ string getline


【解决方案1】:

std::getline(istream&amp;,std::string&amp;) 的工作方式与cin&gt;&gt;var 的工作方式不同。 当您使用cin&gt;&gt;var 时,正确的输入会被正确地吸收到var 中,如果在它之前有一个空格,它会被忽略,但std::getline 不会忽略空格,所以我们使用std::cin.ignore() 来忽略\n。如果你不忽略它,字符串会遇到它,然后不会吸收你的行,因为std::getline() 在遇到\n 时停止。

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

    int main() {
        unsigned n {}, m {};
        cin >> n >> m;

        string set;
        cin.ignore();
        getline(cin, set);
        cout<<set<<endl;
        return 0;
    }

【讨论】:

  • 你能解释一下@anonymous 吗??
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-03-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-06-02
  • 2013-04-28
  • 1970-01-01
相关资源
最近更新 更多