string类输入流
时间: 2023-09-13 08:05:10 浏览: 48
可以使用标准库中的std::getline()函数来读取输入流中的一行字符串,并将其存储到std::string对象中。该函数的原型如下:
```c++
std::istream& getline(std::istream& is, std::string& str, char delim);
```
其中,第一个参数是输入流对象,第二个参数是存储读取结果的std::string对象,第三个参数是用于分隔字符串的字符,可以是换行符、空格、制表符等。
例如,下面的代码读取标准输入流中的一行字符串,并将其存储到名为`input`的std::string对象中:
```c++
#include <iostream>
#include <string>
int main() {
std::string input;
std::getline(std::cin, input);
std::cout << "You entered: " << input << std::endl;
return 0;
}
```
如果需要从文件中读取一行字符串,可以使用std::ifstream类打开文件并将其传递给std::getline()函数的第一个参数。例如:
```c++
#include <iostream>
#include <fstream>
#include <string>
int main() {
std::ifstream infile("test.txt");
std::string line;
while (std::getline(infile, line)) {
std::cout << line << std::endl;
}
return 0;
}
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.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)