
// outfile.cpp -- writing to a file
#include <iostream>
#include <fstream>//庆神握 for file I/O
int main()
{
using namespace std
char automobile[50]
int year
double a_price
double d_price
ofstream outFile // create object for output
outFile.open("carinfo.txt") // associate with a file
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.913 * a_price
// display information on screen with cout
cout <<fixed
cout.precision(2)
cout.setf(ios_base::showpoint)
cout <<"Make and model: " <<automobile <<endl
cout <<"Year: " <<year <<endl
cout <<"Was asking $" <<a_price <<endl
cout <<"Now asking $"誉庆 <<d_price <<endl
// now do exact same things using outFile instead of cout
outFile <<fixed
outFile.precision(2)
outFile.setf(ios_base::showpoint)
outFile <<"Make and model: " <<automobile <<endl
outFile <<"Year: " <<year <<瞎桐 endl
outFile <<"Was asking $" <<a_price <<endl
outFile <<"Now asking $" <<d_price <<endl
outFile.close() // done with file
return 0
}
利用VC软件通过代码书写就可以将数据写入文件。
首先打开VC++6.0。
选择文件,新建。
选择C++ source file 新建一个空白文档。
先声明头文件#include <stdio.h>。
写上主函数
void main
主要代码
FILE *infile,*outfile,*otherfile
char input
char inputs[10]
int i=0
infile = fopen("d:\\infile.txt","r+")//用fopen函数打开文件
outfile = fopen("d:\\outfile.txt","a+")//用fopen函数打开文件
if ( !infile )
printf("open infile failed....\n")
if ( !outfile)
printf("open outfile failed...\n")
printf("兆尘*********************************************\n")
printf("** This program is to show file operation! **\n")
printf("** The input file is: **\n")
printf("** d:\\infile.txt **\n")
printf("** The contents in this file is: **\n")
printf("\n")
for()
{
input = fgetc(infile)//死循环扮渣读出文件厅猜悄内容
printf("%c",input)
putc(input,outfile)//写入内容
i++
if(input == '\n' || input == EOF)
break
}
fclose(infile)
fclose(outfile)
scanf("%d",i)
运行结果
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)