温馨提示×

c++中getline()的用法是什么

c++
小亿
53
2023-12-07 04:49:07
栏目: 编程语言

在C++中,getline()是一个从输入流中读取一行文本的函数。它的用法如下:

#include <iostream>
#include <string>

int main() {
    std::string line;
    std::getline(std::cin, line);
    std::cout << "You entered: " << line << std::endl;
    return 0;
}

在上面的例子中,std::getline()函数从标准输入流(std::cin)中读取一行文本,并将其存储到名为line的字符串变量中。然后,通过std::cout将输入的内容输出到标准输出流中。

std::getline()函数有两个参数:输入流和字符串变量。输入流指定读取文本的源,可以是std::cin、文件输入流或其他输入流。字符串变量是用于存储读取到的文本的变量。

注意,在读取一行文本后,std::getline()函数会丢弃换行符(‘\n’)。如果需要保留换行符,可以使用std::getline()的第三个参数,指定一个结束字符。

例如:

#include <iostream>
#include <string>

int main() {
    std::string line;
    std::getline(std::cin, line, '\n');
    std::cout << "You entered: " << line << std::endl;
    return 0;
}

上面的示例中,std::getline()函数的第三个参数为'\n',表示读取一行文本时,以换行符作为结束字符。这样,换行符将保留在字符串中。

0