简单文件输入/输出

意义与作用较简单,不刻意说明。
1.文本IO和文本文件
刚开始是文本数据,然后,cin对象负责将文本转换为其他类型。
例:输入行是 38.5 19.2
char ch;
cin >> ch;
输入行中的第一个字符被赋值给ch。这里是3,存入ch的是3对应的ASCII码值。
int n;
cin >> n;
这里将不断读取,直到遇到非数字字符。也就是说,读取38,在点这里停止。
double x;
cin >> x;
cin不断读取,直到遇到第一个不属于浮点数的字符。也就是说,读取38.5。在后面空格位置停止。
char word[50];
cin >> word;
cin将不断读取,直到遇到空白字符。
最后看一下另外一种使用char数组来存储输入的情况
char word[50]
cin.getline(word,50);
cin将不断读取,直到遇到换行符(示例输入行少于50个字符)。所有数组都将被存储在数组word中,并在末尾加上一个空字符。

2.写入到文本文件中
    包含头文件iostream,fstream.这个就用代码理解了。
    #include <iostream>
    #include <fstream>

int main()
{
  using namespace std;

  char automobile[50];
  int year;
  double a_price;
  double d_price;

  ofstream outFile;
  outFile.open("carinfo.txt");   //这里是申明一个ofstream对象,再将其与文件关联起来,这样就可以像cout那样使用它了。

  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;
  d_price = 0.94 * a_price;

cout << fixed;
cout.precision(2);
cout.setf(ios_base::showpoint);
cout << "Make and model: " << automobile << endl;
cout << "Yeah: " << year << endl;
cout << "Was asking $" << a_price << endl;
cout << "Now asking $" << d_price << endl;

outFile << fixed;
outFile.precision(2);
outFile.setf(ios_base::showpoint);
outFile << "Make and model: " << automobile <<endl;
outFile << "Yeah: " << year << endl;
outFile << "Was asking $" << a_price << endl;
outFile << "Now asking $" << d_price << endl;

outFile.close();
return 0;

}

3.读取文本文件
2个头文件仍然加上。
首先声明自己的ifstream对象,为其命名,并将其同文件关联起来。
下面演示如何将这种对象与特定的文件关联起来。
inFile.open(“bowling.txt”); //文件对象与文件关联起来
char filename[50];
cin >> filename; //输入你要操作的文件名
fin.open(filename); //fin进行映射
附加:
检查文件是否被成功打开的首先方法是使用方法is_open()。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值