C++实现将输入的内容输出到文本文件
作者:开心的喜茶
这篇文章主要介绍了C++实现将输入的内容输出到文本文件问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教
C++将输入的内容输出到文本文件
将内容输出到文本中要用ofstream这个类来实现。
具体步骤如下:
ofstream mycout(“temp.txt”);//先定义一个ofstream类对象mycout,括号里面的"temp.txt"是我们用来保存输出数据的txt文件名。这里要注意的是我们的"temp.txt"用的是相对路径,你也可以写绝对路径。 mycout<<“hello”<<endl;//这样就把"hello"输出到temp.txt文件中了 mycout.close();//最后要记得关闭打开的文件(这里打开的就是temp.txt文件)
现在给你提供一个完整的程序来实现你说的将输入的内容输出到文件
#include <iostream>
#include <fstream>//ofstream类的头文件
using namespace std;
int main()
{
int n;
cin>>n;
ofstream mycout("temp.txt");
mycout<<n<<endl;
mycout.close();
return 0;
}C++简单文件输入/输出
1、写入到文本文件
- 包含头文件fstream
- 头文件fstream中定义了一个用于处理输出的ofstream类
- 需要声明一个或多个ofstream变量(对象),
- 将ofstream对象与文件关联起来。常用的方法是open()
- 使用完文件后,应使用方法close()将其关闭
- 可结合ofstream对象和运算符<<来输出各种类型的数据
当创建好一个ofstream对象后,便可以像使用cout一样使用它。
#include<iostream>
#include<fstream>
using namespace std;
int main()
{
char automobile[50];
int year;
double a_price;
double b_price;
ofstream outFile;
outFile.open("carimfo.txt");//打开文件,或者创建文件,总之就是和一个文件关联
//默认情况下,open()将首先截断该文件,即将其长度截短到零——丢弃原有内容,将新的输出加入到文件。
cout << "Enter the make and model of automobile:";
cin.getline(automobile, 50);
cout << "Enter the model year:";
cin >> year;
cout << "Enter the original asking price:";
cin >> a_price;
b_price = 0.913 * a_price;
//写入文件
outFile << "Make and model: " << automobile << endl;
outFile << "Year: " << year << endl;
outFile << "Was asking $" << a_price << endl;
outFile << "Now asking $" << b_price << endl;
outFile.close();//关闭文件
system("pause");
return 0;
}2、读取文本文件
其操作和输出相似
#include<iostream>
#include<fstream>
using namespace std;
int main()
{
//创建文件输入对象,并打开
ifstream inFile;
inFile.open("carimfo.txt");
//判断文件是否打开
if (!inFile.is_open())
{
cout << "Could not open the file carimfo.txt" << endl;
cout << "Program terminating.\n";
//函数exit()终止程序 EXIT_FAILURE用于同操作系统通信的参数值
exit(EXIT_FAILURE);
}
double value;
double sum = 0.0;
int count = 0;
while (inFile>>value)
{
//cout<<value<<endl;
count++;
sum += value;
inFile >> value;
}
if (inFile.eof())
cout << "End of file reached.\n";
else if (inFile.fail())
cout << "Input terminated by data mismatch.\n";
else
cout << "Input terminated for unknown reason.\n";
if (count == 0)
cout << "NO data processed.\n";
else{
cout << "Items read: " << count << endl;
cout << "Sum: " << sum << endl;
cout << "Average: " << sum / count << endl;
}
inFile.close();
system("pause");
return 0;
}注意:
Windows文本文件的每行都以回车字符和换行符结尾;通常情况下,C++在读取文件时将这两个字符转换为换行符,并在写入文件时执行相反的转换。
有些文本编辑器,不会在4自动在最后一行末尾加上换行符。
因此,如果读者使用的是这种编辑器,请在输入最后的文本之后按下回车键,再保存文件,否则最后一个数据将出现问题。
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。
