C++ getline() 函数用法详解 - 读取字符串的利器
C++ getline() 函数用法详解 - 读取字符串的利器
getline() 是 C++ 中常用的输入函数,用于从输入流中读取字符串。它比 cin 更加灵活,可以读取包含空格的字符串,并提供对读取字符数量的控制。
1. 读取一行字符串
#include <iostream>
#include <string>
int main() {
std::string str;
std::getline(std::cin, str); // 读取一行字符串
std::cout << str << std::endl; // 输出字符串
return 0;
}
该代码演示了如何使用 getline() 从标准输入流 cin 中读取一行字符串,并存储到 str 变量中。程序会一直读取输入,直到遇到换行符 (\n) 为止。
2. 读取指定字符数的字符串
#include <iostream>
#include <string>
int main() {
std::string str;
std::getline(std::cin, str, ','); // 读取以逗号分隔的字符串
std::cout << str << std::endl; // 输出字符串
return 0;
}
这里,getline() 函数的第三个参数指定了分隔符,在本例中为逗号 (',')。程序会读取输入流中遇到的第一个逗号之前的字符串,并将其存储到 str 变量中。
3. 从文件读取一行字符串
#include <iostream>
#include <fstream>
#include <string>
int main() {
std::string str;
std::ifstream fin("file.txt");
std::getline(fin, str); // 从文件读取一行字符串
std::cout << str << std::endl; // 输出字符串
fin.close();
return 0;
}
这段代码演示了如何使用 getline() 从文件 file.txt 中读取一行字符串。首先,使用 ifstream 对象 fin 打开文件。然后,调用 getline() 函数读取文件的第一行内容并存储到 str 变量中。最后,关闭文件流 fin。
总结:
getline() 函数是 C++ 中处理字符串输入的强大工具。它提供了灵活的读取方式,可以根据需要读取不同的字符串内容,并支持从标准输入流和文件读取数据。
希望本文能够帮助您理解 getline() 函数的用法,并将其应用于您的 C++ 项目中。
原文地址: https://www.cveoy.top/t/topic/nRI5 著作权归作者所有。请勿转载和采集!