#include<iostream> #include<fstream> using namespace std; void test01() { string BookName; string Writer; string Press; int Page = 0; int Cnt = 0; int Price = 0; ofstream ofs; ofs.open("测试文本1.txt", ios::out); cout << "请输入各项数据:"; ofs << "1 " << "2 " << "3 " << "4 " << "5 " << "6 "; } void test02() { ifstream ifs; ifs.open("测试文本1.txt", ios::in); while (!ifs.eof()) { string BookName; string Writer; string Press; int Page = 0; int Cnt = 0; int Price = 0; ifs >> BookName >> Writer >> Press >> Page >> Cnt >> Price; cout << BookName<<" "; cout << Writer << " "; cout << Press << " "; cout << Page << " "; cout << Cnt << " "; cout << Price << " "; }//将所有数据装入vector容器 } int main() { test01(); test02(); return 0; }为什么屏幕上输出会有3个0
时间: 2024-01-25 19:04:44 浏览: 18
根据代码,出现3个0的原因是在 `test01()` 函数中没有对 `Page`、`Cnt` 和 `Price` 进行赋值,而在 `ofs` 流中输出了它们的值。当在 `test02()` 函数中从文件中读取这些值时,由于没有输出它们的实际值,因此输出默认值 0。因此,你可以在 `test01()` 函数中添加代码,为这些变量赋上实际的值,例如:
```
BookName = "《C++ Primer》";
Writer = "Lippman, Lajoie, Moo";
Press = "人民邮电出版社";
Page = 1180;
Cnt = 10;
Price = 99;
```
这样就可以避免在 `test02()` 函数中输出默认值 0。
相关问题
解释代码# include < iostream > # include < string > # include < vector > # include < iomanip > using namespace std ;
这段代码是 C++ 中的预处理指令,用于引入头文件并进行命名空间声明。
- `#include <iostream>` 引入输入输出流库,用于控制台输入输出。
- `#include <string>` 引入字符串库,用于处理字符串操作。
- `#include <vector>` 引入向量库,用于动态数组操作。
- `#include <iomanip>` 引入输入输出流格式化库,用于格式化控制台输出。
`using namespace std;` 是命名空间声明,表示使用标准命名空间(std)中的所有函数和类,避免了每次使用时都要写 std:: 的麻烦。
#include <iostream> #include <queue> #include <string> using namespace std;对代码进行注释
代码注释如下:
```c++
#include <iostream> // 引入输入输出流库
#include <queue> // 引入队列库
#include <string> // 引入字符串库
using namespace std; // 使用 std 命名空间
// 主函数
int main() {
queue<string> q; // 定义一个字符串队列 q
// 往队列中添加元素
q.push("apple");
q.push("banana");
q.push("orange");
// 输出队列头部元素
cout << q.front() << endl; // 输出:apple
// 弹出队列头部元素
q.pop();
// 输出队列头部元素
cout << q.front() << endl; // 输出:banana
// 输出队列中元素的个数
cout << "The size of the queue is " << q.size() << endl; // 输出:The size of the queue is 2
return 0; // 返回 0 表示程序正常结束
}
```