``` getline ```两种用法
时间: 2024-06-01 07:07:04 浏览: 17
`getline` 是 C++ 标准库中的一个函数,用于从输入流中读取一行字符,并将其存储到一个字符串中。`getline` 函数有两种常用的用法:
1. 从标准输入流中读取一行字符并存储到字符串中:
```c++
#include <iostream>
#include <string>
int main() {
std::string line;
std::getline(std::cin, line); // 从标准输入流中读取一行字符
std::cout << "你输入的内容是:" << line << std::endl;
return 0;
}
```
2. 从文件流中读取一行字符并存储到字符串中:
```c++
#include <iostream>
#include <fstream>
#include <string>
int main() {
std::ifstream ifs("test.txt");
if (!ifs) {
std::cerr << "打开文件失败" << std::endl;
return -1;
}
std::string line;
while (std::getline(ifs, line)) { // 从文件流中读取一行字符
std::cout << line << std::endl;
}
return 0;
}
```
以上两种用法都是调用 `getline` 函数,并将输入流对象(例如 `std::cin` 或 `std::ifstream`)和一个字符串对象作为参数传递给函数,函数会读取输入流中的一行字符,并将其存储到字符串对象中。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)