C++ 的输入与输出包括以下3方面的内容:
(1) 对系统指定的标准设备的输入和输出。即从键盘输入数据,输出到显示器屏幕。这种输入输出称为标准的输入输出,简称标准 I/O 。
(2) 以外存磁盘文件为对象进行输入和输出,即从磁盘文件输入数据,数据输出到磁盘文件。以外存文件为对象的输入输出称为文件的输入输出,简称文件 I/O 。
(3) 对内存中指定的空间进行输入和输出。通常指定一个字符数组作为存储空间(实际上可以利用该空间存储任何信息)。这种输入和输出称为字符串输入输出,简称串 I/O 。
常用的输入输出流如下:
类名 | 作用 | 头文件 |
---|---|---|
istream | 通用输入流 | iostream |
ostream | 通用输出流 | iostream |
iostream | 通用输入输出流 | iostream |
ifstream | 文件输入流 | fstream |
ofstream | 文件输出流 | fstream |
fstream | 文件输入输出流 | fstream |
istringstream | 字符串输入流 | sstream |
ostringstream | 字符串输出流 | sstream |
stringstream | 字符串输入输出流 | sstream |
C++输入输出流(IO流)有四种状态标志,用于指示流的当前状态。这些状态对于错误处理和流控制非常重要。
goodbit (0)
含义:表示流处于正常状态,没有错误发生
检测方法:stream.good()
特点:当流可以正常读写时,goodbit被设置
1std::ifstream file("example.txt");
2if (file.good()) {
3 std::cout << "文件打开成功,可以读取" << std::endl;
4}
eofbit (1)
含义:表示已经到达输入流的末尾(End Of File)
检测方法:stream.eof()
特点:当尝试读取超过文件末尾的数据时,eofbit被设置
xxxxxxxxxx
81std::ifstream file("example.txt");
2std::string content;
3while (file >> content) {
4 // 处理内容
5}
6if (file.eof()) {
7 std::cout << "已到达文件末尾" << std::endl;
8}
failbit (2)
含义:表示发生了可恢复的错误,如格式错误
检测方法:stream.fail()
特点:当输入不符合预期格式时,failbit被设置
xxxxxxxxxx
61std::istringstream iss("abc");
2int number;
3iss >> number; // 尝试将字符串转换为整数
4if (iss.fail()) {
5 std::cout << "格式转换失败" << std::endl;
6}
badbit (4)
含义:表示发生了不可恢复的错误,如IO错误
检测方法:stream.bad()
特点:当流遇到严重错误时,badbit被设置
xxxxxxxxxx
41std::ofstream file("nonexistent_directory/file.txt");
2if (file.bad()) {
3 std::cout << "发生严重错误,无法写入文件" << std::endl;
4}
除了上述特定状态检查函数外,还有一些综合性的检查函数:
operator bool() 或 !stream
当流处于可用状态时返回true,否则返回false
等价于 !fail()
,即检查failbit和badbit都未设置
x1std::ifstream file("example.txt");
2if (file) { // 隐式转换为bool
3 std::cout << "文件可用" << std::endl;
4}
5
6if (!file) {
7 std::cout << "文件不可用" << std::endl;
8}
stream.rdstate()
返回当前流的所有状态标志
返回值是一个位掩码,可以与状态常量进行位操作
xxxxxxxxxx
51std::ifstream file("example.txt");
2std::ios_base::iostate state = file.rdstate();
3if (state & std::ios_base::eofbit) {
4 std::cout << "EOF标志被设置" << std::endl;
5}
stream.clear()
清除所有错误标志,将流状态重置为goodbit
如果底层IO设备仍有问题,可能无法完全恢复
xxxxxxxxxx
81std::istringstream iss("abc");
2int number;
3iss >> number; // 失败,设置failbit
4if (iss.fail()) {
5 iss.clear(); // 清除错误标志
6 std::string text;
7 iss >> text; // 现在可以正常读取字符串
8}
stream.clear(state)
将流状态设置为指定的状态
可以选择性地设置或清除特定标志
xxxxxxxxxx
31std::ifstream file("example.txt");
2// 手动设置eofbit
3file.clear(std::ios_base::eofbit);
stream.setstate(state)
在当前状态基础上添加新的错误标志
不会清除已有的错误标志
xxxxxxxxxx
31std::ifstream file("example.txt");
2// 添加failbit标志,不影响其他标志
3file.setstate(std::ios_base::failbit);
文件操作错误处理
xxxxxxxxxx
181std::ifstream file("data.txt");
2if (!file) {
3 std::cerr << "无法打开文件" << std::endl;
4 return 1;
5}
6
7int value;
8while (file >> value) {
9 // 处理数据
10}
11
12if (file.eof()) {
13 std::cout << "文件读取完毕" << std::endl;
14} else if (file.fail()) {
15 std::cerr << "读取过程中遇到格式错误" << std::endl;
16} else if (file.bad()) {
17 std::cerr << "读取过程中遇到严重IO错误" << std::endl;
18}
输入验证
xxxxxxxxxx
121int getUserInput() {
2 int input;
3 std::cout << "请输入一个整数: ";
4
5 while (!(std::cin >> input)) {
6 std::cin.clear(); // 清除错误标志
7 std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); // 忽略错误输入
8 std::cout << "输入无效,请重新输入一个整数: ";
9 }
10
11 return input;
12}
格式化输入输出
xxxxxxxxxx
101std::istringstream iss("123 abc 456");
2int a, b;
3std::string s;
4
5iss >> a >> s >> b;
6if (iss.fail()) {
7 std::cout << "格式不匹配" << std::endl;
8} else {
9 std::cout << "a=" << a << ", s=" << s << ", b=" << b << std::endl;
10}
C++标准输入流是C++标准库中用于处理输入操作的一部分,主要通过<iostream>
头文件中的std::cin
对象实现。
基本输入
xxxxxxxxxx
101
2using namespace std;
3
4int main() {
5 int num;
6 cout << "请输入一个整数:";
7 cin >> num;
8 cout << "您输入的整数是:" << num << endl;
9 return 0;
10}
连续输入多个值
xxxxxxxxxx
101
2using namespace std;
3
4int main() {
5 int a, b, c;
6 cout << "请输入三个整数,用空格分隔:";
7 cin >> a >> b >> c;
8 cout << "您输入的三个整数是:" << a << ", " << b << ", " << c << endl;
9 return 0;
10}
cin
对象有几个状态标志,可以用来检查输入操作是否成功:
xxxxxxxxxx
181
2using namespace std;
3
4int main() {
5 int num;
6 cout << "请输入一个整数:";
7 cin >> num;
8
9 if (cin.good()) {
10 cout << "输入成功!" << endl;
11 } else if (cin.fail()) {
12 cout << "输入失败!" << endl;
13 cin.clear(); // 清除错误状态
14 cin.ignore(numeric_limits<streamsize>::max(), '\n'); // 忽略错误输入
15 }
16
17 return 0;
18}
cin.get()
- 读取单个字符
xxxxxxxxxx
11char ch = cin.get(); // 读取一个字符
cin.getline()
- 读取一行
xxxxxxxxxx
21char str[100];
2cin.getline(str, 100); // 读取最多99个字符或遇到换行符停止
cin.ignore()
- 忽略字符
xxxxxxxxxx
11cin.ignore(100, '\n'); // 忽略最多100个字符或遇到换行符停止
cin.peek()
- 查看下一个字符但不取出
xxxxxxxxxx
11char next = cin.peek(); // 查看下一个字符
cin.clear()
- 清除错误状态
xxxxxxxxxx
11cin.clear(); // 重置cin的状态标志
xxxxxxxxxx
181
2
3
4using namespace std;
5
6int main() {
7 string line;
8 cout << "请输入一行数字,用空格分隔:";
9 getline(cin, line);
10
11 istringstream iss(line);
12 int num;
13 while (iss >> num) {
14 cout << "读取到数字:" << num << endl;
15 }
16
17 return 0;
18}
xxxxxxxxxx
241
2
3using namespace std;
4
5int main() {
6 int num;
7 bool valid_input = false;
8
9 while (!valid_input) {
10 cout << "请输入一个整数:";
11 cin >> num;
12
13 if (cin.fail()) {
14 cout << "输入无效,请重试!" << endl;
15 cin.clear();
16 cin.ignore(numeric_limits<streamsize>::max(), '\n');
17 } else {
18 valid_input = true;
19 }
20 }
21
22 cout << "您输入的有效整数是:" << num << endl;
23 return 0;
24}
Note
输入操作可能会失败,特别是当输入的数据类型与变量类型不匹配时。
使用cin
读取数值后,缓冲区中可能会留下换行符,这可能会影响后续的输入操作。
对于读取整行文本,建议使用getline()
函数而不是cin >>
操作符。
C++标准输出流是C++标准库中用于处理输出操作的一部分,主要通过<iostream>
头文件中的std::cout
对象实现。
基本输出
xxxxxxxxxx
71
2using namespace std;
3
4int main() {
5 cout << "Hello, World!" << endl;
6 return 0;
7}
输出多个值
xxxxxxxxxx
91
2using namespace std;
3
4int main() {
5 int age = 25;
6 string name = "张三";
7 cout << "姓名: " << name << ", 年龄: " << age << endl;
8 return 0;
9}
使用<iomanip>
库
xxxxxxxxxx
201
2// 用于格式化输出
3using namespace std;
4
5int main() {
6 double pi = 3.14159265358979;
7
8 // 设置精度
9 cout << "默认精度: " << pi << endl;
10 cout << "固定精度: " << fixed << setprecision(4) << pi << endl;
11
12 // 设置宽度和对齐
13 cout << setw(10) << right << "右对齐" << endl;
14 cout << setw(10) << left << "左对齐" << endl;
15
16 // 设置填充字符
17 cout << setfill('*') << setw(10) << "填充" << endl;
18
19 return 0;
20}
使用流操纵算子
xxxxxxxxxx
161
2using namespace std;
3
4int main() {
5 // 进制转换
6 int num = 255;
7 cout << "十进制: " << dec << num << endl;
8 cout << "十六进制: " << hex << num << endl;
9 cout << "八进制: " << oct << num << endl;
10
11 // 布尔值显示
12 cout << boolalpha << true << " " << false << endl; // 显示为true false
13 cout << noboolalpha << true << " " << false << endl; // 显示为1 0
14
15 return 0;
16}
cout.width()
- 设置宽度
xxxxxxxxxx
21cout.width(10);
2cout << "宽度为10" << endl;
cout.precision()
- 设置精度
xxxxxxxxxx
21cout.precision(4);
2cout << 3.14159265358979 << endl; // 输出3.142
cout.fill()
- 设置填充字符
xxxxxxxxxx
31cout.fill('*');
2cout.width(10);
3cout << "填充" << endl; // 输出******填充
cout.flush()
- 刷新缓冲区
xxxxxxxxxx
21cout << "立即显示";
2cout.flush(); // 立即刷新输出缓冲区
可以通过重载<<
运算符来实现自定义类的输出:
xxxxxxxxxx
261
2using namespace std;
3
4class Person {
5private:
6 string name;
7 int age;
8
9public:
10 Person(string n, int a) : name(n), age(a) {}
11
12 // 声明友元函数
13 friend ostream& operator<<(ostream& os, const Person& p);
14};
15
16// 重载<<运算符
17ostream& operator<<(ostream& os, const Person& p) {
18 os << "Person(name=" << p.name << ", age=" << p.age << ")";
19 return os;
20}
21
22int main() {
23 Person p("李四", 30);
24 cout << p << endl;
25 return 0;
26}
使用<fstream>
库可以将输出重定向到文件:
xxxxxxxxxx
181
2
3using namespace std;
4
5int main() {
6 ofstream outFile("output.txt");
7
8 if (outFile.is_open()) {
9 outFile << "这是写入文件的内容" << endl;
10 outFile << "第二行内容" << endl;
11 outFile.close();
12 cout << "文件写入成功!" << endl;
13 } else {
14 cout << "无法打开文件!" << endl;
15 }
16
17 return 0;
18}
使用<sstream>
库可以将输出重定向到字符串:
xxxxxxxxxx
151
2
3
4using namespace std;
5
6int main() {
7 ostringstream oss;
8
9 oss << "姓名: " << "王五" << ", 年龄: " << 35;
10 string result = oss.str();
11
12 cout << "字符串流内容: " << result << endl;
13
14 return 0;
15}
Note
输出操作可能会受到缓冲区的影响,使用endl
或flush()
可以立即刷新缓冲区。
格式化设置(如精度、宽度等)通常只影响下一次输出操作。
在多线程环境中,标准输出流可能需要同步机制来避免输出混乱。
文件输入流(File Input Stream)是C++标准库提供的用于从文件读取数据的机制,主要通过<fstream>
头文件中的std::ifstream
类实现。
1. 包含必要的头文件
xxxxxxxxxx
31// 文件流
2// 标准输入输出流
3// 字符串处理
2. 打开文件
xxxxxxxxxx
61// 方法1:构造函数打开
2std::ifstream inFile("data.txt");
3
4// 方法2:先创建对象,再打开文件
5std::ifstream inFile2;
6inFile2.open("data.txt");
3. 检查文件是否成功打开
xxxxxxxxxx
101std::ifstream inFile("data.txt");
2if (!inFile) {
3 std::cerr << "无法打开文件!" << std::endl;
4 return 1;
5}
6// 或者使用is_open()
7if (!inFile.is_open()) {
8 std::cerr << "无法打开文件!" << std::endl;
9 return 1;
10}
4. 读取文件内容
逐字符读取
xxxxxxxxxx
41char ch;
2while (inFile.get(ch)) {
3 std::cout << ch;
4}
按行读取
xxxxxxxxxx
41std::string line;
2while (std::getline(inFile, line)) {
3 std::cout << line << std::endl;
4}
读取格式化数据
xxxxxxxxxx
81int num;
2double value;
3std::string name;
4
5// 假设文件每行包含:整数 浮点数 字符串
6while (inFile >> num >> value >> name) {
7 std::cout << "读取到:" << num << ", " << value << ", " << name << std::endl;
8}
5. 文件定位
xxxxxxxxxx
111// 移动到文件开头
2inFile.seekg(0, std::ios::beg);
3
4// 移动到文件末尾
5inFile.seekg(0, std::ios::end);
6
7// 移动到文件中的第10个字节
8inFile.seekg(10, std::ios::beg);
9
10// 获取当前位置
11std::streampos position = inFile.tellg();
6. 关闭文件
xxxxxxxxxx
11inFile.close();
xxxxxxxxxx
121// 以二进制模式打开文件
2std::ifstream binFile("data.bin", std::ios::binary);
3
4// 读取二进制数据
5struct Data {
6 int id;
7 double value;
8 char name[50];
9};
10
11Data data;
12binFile.read(reinterpret_cast<char*>(&data), sizeof(Data));
xxxxxxxxxx
201std::ifstream file("data.txt");
2
3// 检查各种错误状态
4if (file.fail()) {
5 std::cerr << "打开文件失败!" << std::endl;
6}
7
8// 读取过程中的错误处理
9int value;
10file >> value;
11if (file.fail()) {
12 std::cerr << "读取失败,可能是格式不匹配" << std::endl;
13 file.clear(); // 清除错误标志
14 file.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); // 跳过当前行
15}
16
17// 检查是否到达文件末尾
18if (file.eof()) {
19 std::cout << "已到达文件末尾" << std::endl;
20}
xxxxxxxxxx
421
2
3
4
5
6int main() {
7 // 打开文件
8 std::ifstream inFile("students.txt");
9
10 // 检查文件是否成功打开
11 if (!inFile) {
12 std::cerr << "无法打开文件!" << std::endl;
13 return 1;
14 }
15
16 // 读取并显示文件内容
17 std::string name;
18 int age;
19 double score;
20
21 std::cout << "学生信息:" << std::endl;
22 std::cout << "---------------------------" << std::endl;
23 std::cout << "姓名\t年龄\t分数" << std::endl;
24 std::cout << "---------------------------" << std::endl;
25
26 // 逐行读取格式化数据
27 while (inFile >> name >> age >> score) {
28 std::cout << name << "\t" << age << "\t" << score << std::endl;
29 }
30
31 // 检查是否因为错误而结束
32 if (inFile.bad()) {
33 std::cerr << "读取文件时发生严重错误!" << std::endl;
34 } else if (inFile.fail() && !inFile.eof()) {
35 std::cerr << "读取格式不匹配!" << std::endl;
36 }
37
38 // 关闭文件
39 inFile.close();
40
41 return 0;
42}
open(filename, mode)
: 打开文件
close()
: 关闭文件
is_open()
: 检查文件是否打开
eof()
: 检查是否到达文件末尾
fail()
: 检查操作是否失败
bad()
: 检查是否发生严重错误
good()
: 检查流是否处于良好状态
clear()
: 清除错误标志
seekg()
: 设置读取位置
tellg()
: 获取当前读取位置
read()
: 读取二进制数据
get()
: 读取单个字符
getline()
: 读取一行文本
ignore()
: 忽略字符
std::ios::in
: 读取模式(默认)
std::ios::binary
: 二进制模式
std::ios::ate
: 打开后立即定位到文件末尾
std::ios::app
: 追加模式
可以组合使用,例如:
xxxxxxxxxx
11std::ifstream file("data.bin", std::ios::in | std::ios::binary);
Note
始终检查文件是否成功打开
读取完成后关闭文件
处理可能的读取错误
对于二进制文件,使用std::ios::binary
模式
使用seekg()
和tellg()
进行文件定位时要小心
大文件读取考虑使用缓冲区提高效率
文件输出流(File Output Stream)是C++标准库提供的用于向文件写入数据的机制,主要通过<fstream>
头文件中的std::ofstream
类实现。
1. 包含必要的头文件
xxxxxxxxxx
31// 文件流
2// 标准输入输出流
3// 字符串处理
2. 创建和打开文件
xxxxxxxxxx
61// 方法1:构造函数打开
2std::ofstream outFile("output.txt");
3
4// 方法2:先创建对象,再打开文件
5std::ofstream outFile2;
6outFile2.open("output.txt");
3. 检查文件是否成功打开
xxxxxxxxxx
101std::ofstream outFile("output.txt");
2if (!outFile) {
3 std::cerr << "无法打开文件!" << std::endl;
4 return 1;
5}
6// 或者使用is_open()
7if (!outFile.is_open()) {
8 std::cerr << "无法打开文件!" << std::endl;
9 return 1;
10}
4. 写入文件内容
使用插入运算符(<<)
xxxxxxxxxx
21outFile << "Hello, World!" << std::endl;
2outFile << 42 << " " << 3.14 << " " << "C++" << std::endl;
逐字符写入
xxxxxxxxxx
71char ch = 'A';
2outFile.put(ch);
3
4std::string str = "Hello";
5for (char c : str) {
6 outFile.put(c);
7}
写入原始数据
xxxxxxxxxx
21const char* data = "Raw data";
2outFile.write(data, strlen(data));
5. 文件打开模式
xxxxxxxxxx
141// 覆盖模式(默认)
2std::ofstream file1("file1.txt");
3
4// 追加模式
5std::ofstream file2("file2.txt", std::ios::app);
6
7// 二进制模式
8std::ofstream file3("file3.dat", std::ios::binary);
9
10// 截断模式(如果文件存在则清空内容)
11std::ofstream file4("file4.txt", std::ios::trunc);
12
13// 组合模式
14std::ofstream file5("file5.dat", std::ios::app | std::ios::binary);
6. 文件定位
xxxxxxxxxx
111// 移动到文件开头
2outFile.seekp(0, std::ios::beg);
3
4// 移动到文件末尾
5outFile.seekp(0, std::ios::end);
6
7// 移动到文件中的第10个字节
8outFile.seekp(10, std::ios::beg);
9
10// 获取当前位置
11std::streampos position = outFile.tellp();
7. 关闭文件
xxxxxxxxxx
11outFile.close();
xxxxxxxxxx
121// 以二进制模式打开文件
2std::ofstream binFile("data.bin", std::ios::binary);
3
4// 写入二进制数据
5struct Data {
6 int id;
7 double value;
8 char name[50];
9};
10
11Data data = {1, 3.14, "Example"};
12binFile.write(reinterpret_cast<const char*>(&data), sizeof(Data));
xxxxxxxxxx
151std::ofstream file("output.txt");
2
3// 检查各种错误状态
4if (file.fail()) {
5 std::cerr << "打开文件失败!" << std::endl;
6}
7
8// 写入过程中的错误处理
9file << 100;
10if (file.bad()) {
11 std::cerr << "写入时发生严重错误!" << std::endl;
12}
13
14// 清除错误标志
15file.clear();
xxxxxxxxxx
191
2
3std::ofstream file("formatted.txt");
4
5// 设置浮点数精度
6file << std::fixed << std::setprecision(2);
7file << 3.14159265 << std::endl; // 输出:3.14
8
9// 设置字段宽度和填充字符
10file << std::setw(10) << std::setfill('*') << 42 << std::endl; // 输出:********42
11
12// 设置对齐方式
13file << std::left << std::setw(10) << "Left" << std::endl; // 输出:Left******
14file << std::right << std::setw(10) << "Right" << std::endl; // 输出:*****Right
15
16// 设置数字进制
17file << std::hex << 255 << std::endl; // 输出:ff
18file << std::oct << 255 << std::endl; // 输出:377
19file << std::dec << 255 << std::endl; // 输出:255
xxxxxxxxxx
541
2
3
4
5
6int main() {
7 // 打开文件
8 std::ofstream outFile("students.txt");
9
10 // 检查文件是否成功打开
11 if (!outFile) {
12 std::cerr << "无法打开文件!" << std::endl;
13 return 1;
14 }
15
16 // 准备写入的学生数据
17 struct Student {
18 std::string name;
19 int age;
20 double score;
21 };
22
23 Student students[] = {
24 {"张三", 20, 85.5},
25 {"李四", 22, 92.0},
26 {"王五", 21, 78.5}
27 };
28
29 // 写入表头
30 outFile << "姓名 年龄 分数" << std::endl;
31 outFile << "------------------" << std::endl;
32
33 // 设置浮点数格式
34 outFile << std::fixed << std::setprecision(1);
35
36 // 写入学生数据
37 for (const auto& student : students) {
38 outFile << student.name << " "
39 << student.age << " "
40 << student.score << std::endl;
41 }
42
43 // 检查是否发生错误
44 if (outFile.fail()) {
45 std::cerr << "写入文件时发生错误!" << std::endl;
46 }
47
48 // 关闭文件
49 outFile.close();
50
51 std::cout << "数据已成功写入到students.txt文件中。" << std::endl;
52
53 return 0;
54}
open(filename, mode)
: 打开文件
close()
: 关闭文件
is_open()
: 检查文件是否打开
fail()
: 检查操作是否失败
bad()
: 检查是否发生严重错误
good()
: 检查流是否处于良好状态
clear()
: 清除错误标志
flush()
: 刷新输出缓冲区
seekp()
: 设置写入位置
tellp()
: 获取当前写入位置
write()
: 写入二进制数据
put()
: 写入单个字符
std::ios::out
: 输出模式(默认)
std::ios::app
: 追加模式
std::ios::ate
: 打开后立即定位到文件末尾
std::ios::trunc
: 如果文件存在则截断(默认)
std::ios::binary
: 二进制模式
可以组合使用,例如:
xxxxxxxxxx
11std::ofstream file("data.bin", std::ios::out | std::ios::binary | std::ios::app);
Note
始终检查文件是否成功打开
写入完成后关闭文件
处理可能的写入错误
对于二进制文件,使用std::ios::binary
模式
使用flush()
或endl
确保数据及时写入磁盘
默认情况下,打开已存在的文件会清空其内容,如需追加请使用std::ios::app
模式
写入大量数据时,考虑使用缓冲区提高效率
在多线程环境中,确保适当的同步机制
如果需要同时读写一个文件,可以使用std::fstream
类:
xxxxxxxxxx
101
2
3std::fstream file("data.txt", std::ios::in | std::ios::out);
4
5// 读取数据
6int value;
7file >> value;
8
9// 写入数据
10file << "New data";
字符串输入流(istringstream)是C++标准库中的一个类,它允许像处理输入流一样处理字符串。它属于<sstream>
头文件中定义的一组类之一。
xxxxxxxxxx
221
2
3
4
5int main() {
6 // 创建一个字符串
7 std::string str = "123 456 789";
8
9 // 创建一个istringstream对象,并用字符串初始化
10 std::istringstream iss(str);
11
12 // 从字符串流中读取数据
13 int a, b, c;
14 iss >> a >> b >> c;
15
16 // 输出读取的数据
17 std::cout << "a = " << a << std::endl;
18 std::cout << "b = " << b << std::endl;
19 std::cout << "c = " << c << std::endl;
20
21 return 0;
22}
1.字符串解析:将字符串分割成多个部分或转换为不同的数据类型
xxxxxxxxxx
81std::string input = "apple 10 3.14";
2std::istringstream iss(input);
3
4std::string fruit;
5int quantity;
6double price;
7
8iss >> fruit >> quantity >> price;
2.格式转换:将字符串转换为数值类型
xxxxxxxxxx
41std::string numStr = "42";
2std::istringstream iss(numStr);
3int num;
4iss >> num; // num = 42
3.按行处理:结合getline()函数处理多行文本
xxxxxxxxxx
71std::string text = "Line1\nLine2\nLine3";
2std::istringstream iss(text);
3std::string line;
4
5while (std::getline(iss, line)) {
6 std::cout << line << std::endl;
7}
4.CSV文件解析:处理逗号分隔的数据
xxxxxxxxxx
71std::string csvLine = "John,25,New York";
2std::istringstream iss(csvLine);
3std::string name, age, city;
4
5getline(iss, name, ',');
6getline(iss, age, ',');
7getline(iss, city, ',');
str():获取或设置字符串流的内容
clear():清除错误状态
good():检查流是否处于良好状态
eof():检查是否到达流的末尾
fail():检查是否有操作失败
Note
类型转换失败时会设置流的失败状态
可以使用clear()方法重置流的状态
使用前需要包含<sstream>
头文件
字符串输出流(ostringstream)是C++标准库中的一个类,它允许将数据写入到一个字符串缓冲区中,就像写入到标准输出流一样。它属于<sstream>
头文件中定义的一组类之一。
xxxxxxxxxx
211
2
3
4
5int main() {
6 // 创建一个ostringstream对象
7 std::ostringstream oss;
8
9 // 向字符串流中写入数据
10 oss << "Hello, " << "World!" << std::endl;
11 oss << "数字: " << 42 << std::endl;
12 oss << "浮点数: " << 3.14 << std::endl;
13
14 // 获取构建的字符串
15 std::string result = oss.str();
16
17 // 输出结果
18 std::cout << result;
19
20 return 0;
21}
1.字符串构建:将不同类型的数据组合成一个字符串
xxxxxxxxxx
71std::ostringstream oss;
2int id = 101;
3std::string name = "张三";
4double score = 95.5;
5
6oss << "学生ID: " << id << ", 姓名: " << name << ", 成绩: " << score;
7std::string studentInfo = oss.str();
2.格式化输出:使用格式化标志控制输出格式
xxxxxxxxxx
41std::ostringstream oss;
2oss << std::fixed << std::setprecision(2);
3oss << "价格: " << 10.3456 << "元"; // 输出: "价格: 10.35元"
4std::string priceInfo = oss.str();
3.数值转字符串:将数值类型转换为字符串
xxxxxxxxxx
41int num = 42;
2std::ostringstream oss;
3oss << num;
4std::string numStr = oss.str(); // numStr = "42"
4.构建复杂字符串:例如构建XML、JSON或其他格式化文本
xxxxxxxxxx
61std::ostringstream xml;
2xml << "<person>\n";
3xml << " <name>李四</name>\n";
4xml << " <age>30</age>\n";
5xml << "</person>\n";
6std::string xmlStr = xml.str();
str():获取当前字符串流中的内容
str(string):设置字符串流的内容
clear():清除错误状态
seekp():设置写入位置
tellp():获取当前写入位置
Note
使用前需要包含<sstream>
头文件
如果需要格式化输出,还需要包含<iomanip>
头文件
可以使用str("")
或创建新的ostringstream对象来清空内容
对于大量的字符串操作,ostringstream通常比多次使用+运算符拼接字符串更高效
xxxxxxxxxx
31// 清空字符串流
2oss.str("");
3oss.clear(); // 同时清除错误状态