📅  最后修改于: 2023-12-03 15:29:55.561000             🧑  作者: Mango
这个套装是一个集合了多个 C++ 程序输出的示例,涵盖了常见的输出方式和输出情景,旨在帮助程序员更好地理解 C++ 输出相关的知识点。
以下是套装中包含的所有 C++ 程序输出示例:
接下来,我们将逐一介绍每一个示例的输出效果和对应源代码。
#include <iostream>
int main() {
std::cout << "Hello, World!";
return 0;
}
输出结果:
Hello, World!
#include <iostream>
int main() {
std::cout << "Line 1" << std::endl;
std::cout << "Line 2" << std::endl;
std::cout << "Line 3" << std::endl;
std::cout << "Line 4";
return 0;
}
输出结果:
Line 1
Line 2
Line 3
Line 4
#include <iostream>
#include <iomanip>
int main() {
int a = 123;
std::cout << "Decimal: " << a << std::endl;
std::cout << "Hexadecimal: " << std::hex << std::showbase << a << std::endl;
std::cout << "Octal: " << std::oct << a << std::endl;
double b = 1.23456789;
std::cout.precision(4); // 设置精度为小数点后4位
std::cout << std::fixed << "Fixed-point notation: " << b << std::endl;
std::cout << "Scientific notation: " << std::scientific << b << std::endl;
return 0;
}
输出结果:
Decimal: 123
Hexadecimal: 0x7b
Octal: 173
Fixed-point notation: 1.2346
Scientific notation: 1.2346e+00
#include <iostream>
#include <fstream>
int main() {
// 输出到文件
std::ofstream fout("output.txt");
std::streambuf* old_cout = std::cout.rdbuf();
std::cout.rdbuf(fout.rdbuf());
std::cout << "Hello, World!\n";
std::cout.rdbuf(old_cout);
fout.close();
// 从文件读取
std::ifstream fin("input.txt");
std::streambuf* old_cin = std::cin.rdbuf();
std::cin.rdbuf(fin.rdbuf());
int a, b;
std::cin >> a >> b;
std::cout << "Sum: " << a + b << std::endl;
std::cin.rdbuf(old_cin);
fin.close();
return 0;
}
output.txt 文件内容:
Hello, World!
input.txt 文件内容:
1 2
输出结果:
Sum: 3
#include <iostream>
#include <fstream>
int main() {
std::ofstream fout("output.txt");
fout << "Line 1\n";
fout << "Line 2\n";
fout.close();
return 0;
}
output.txt 文件内容:
Line 1
Line 2
#include <iostream>
#include <fstream>
int main() {
// 输出到标准错误流
std::cerr << "Error: Invalid operation!" << std::endl;
// 输出到文件
std::ofstream log("log.txt");
log << "[Info] Program started." << std::endl;
log << "[Error] Invalid input." << std::endl;
log << "[Info] Program exited." << std::endl;
log.close();
return 0;
}
log.txt 文件内容:
[Info] Program started.
[Error] Invalid input.
[Info] Program exited.
以上就是 C++ 程序输出套装18的全部内容,希望能够对您有所帮助!