c++输出到txt文件
时间: 2023-08-17 08:09:30 浏览: 50
在 C++ 中,可以使用文件流来将输出内容写入到文本文件中。下面是一个基本的示例:
```c++
#include <iostream>
#include <fstream>
int main() {
std::ofstream outfile("output.txt"); // 创建一个名为 "output.txt" 的文件流对象
outfile << "Hello, world!"; // 将字符串写入文件
outfile.close(); // 关闭文件流
return 0;
}
```
在上述示例中,我们使用 `ofstream` 类创建一个名为 "output.txt" 的文件流对象。然后,我们使用 `<<` 运算符将字符串 "Hello, world!" 写入到该文件中。最后,我们调用 `close()` 方法关闭文件流。
如果要写入多个内容,可以多次使用 `<<` 运算符。每次使用时,都会将内容写入到文件中。
如果要追加内容到文件末尾,而不是覆盖原有内容,可以使用 `std::ios::app` 模式打开文件流:
```c++
std::ofstream outfile("output.txt", std::ios::app);
```
这样就可以将新的内容追加到文件末尾了。
相关问题
c++输出到文本文件
要将 C++ 程序的输出内容写入文本文件,可以使用以下步骤:
1. 包含头文件 `fstream`。
```c++
#include <fstream>
```
2. 创建 `ofstream` 对象并打开文件。`ofstream` 是一个用于写入文件的输出流对象。通过打开文件,你可以将输出写入文件而不是控制台。
```c++
std::ofstream outfile;
outfile.open("output.txt");
```
3. 将输出写入文件。将需要输出的内容作为字符串参数传递给 `outfile` 对象的 `<<` 运算符。
```c++
outfile << "Hello, World!" << std::endl;
```
4. 关闭文件。
```c++
outfile.close();
```
完整的代码示例:
```c++
#include <fstream>
int main() {
std::ofstream outfile;
outfile.open("output.txt");
outfile << "Hello, World!" << std::endl;
outfile.close();
return 0;
}
```
这将把 "Hello, World!" 写入到名为 "output.txt" 的文件中。
c++ printf输出到文件
在 C++ 中,也可以使用 `fprintf` 函数将输出内容输出到文件中。与 C 语言类似,具体用法如下:
```c++
#include <iostream>
#include <cstdio>
int main() {
FILE* fp; // 文件指针
fp = fopen("output.txt", "w"); // 打开文件
if (fp == NULL) { // 检查文件是否成功打开
std::cout << "Failed to open file!" << std::endl;
return 1;
}
fprintf(fp, "Hello, world!\n"); // 输出到文件
fclose(fp); // 关闭文件
return 0;
}
```
在这个示例中,使用了 `<cstdio>` 头文件中的 `FILE` 类型和 `fopen` 函数。与 C 语言不同的是,这里使用了 `std::cout` 来输出错误信息。使用 `fprintf` 函数将输出内容输出到文件中,最后使用 `fclose` 函数关闭文件。
需要注意的是,`fprintf` 函数的第一个参数是文件指针,后面的参数与 `printf` 函数的用法类似,可以输出格式化字符串以及其他变量。输出的内容会被写入到文件中,不会在控制台上显示。