getline是一个C++标准库函数,用于从输入流中读取一行字符串。它的基本用法如下:

#include <iostream>
#include <string>

using namespace std;

int main() {
    string line;
    getline(cin, line);
    cout << "输入的字符串是:" << line << endl;
    return 0;
}

上面的代码使用了getline函数从标准输入流(cin)中读取一行字符串,并将结果存储在一个名为line的string对象中。读取的字符串可以包含空格和其他空白字符,直到遇到换行符为止。

getline函数有两个参数,第一个参数是输入流对象,第二个参数是存储读取结果的字符串对象。如果输入流中没有更多的数据可读取,getline函数将返回false。如果读取成功,getline函数将返回true。

如果您需要读取多个行,可以使用循环来重复调用getline函数,例如:

#include <iostream>
#include <string>

using namespace std;

int main() {
    string line;
    while (getline(cin, line)) {
        cout << "输入的字符串是:" << line << endl;
    }
    return 0;
}

上面的代码将不断从标准输入流中读取行,直到遇到输入流的结尾为止

getline的用法

原文地址: https://www.cveoy.top/t/topic/eqVs 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录