1 #include<iostream>
2 #include<fstream>
3 using namespace std;
4
5 int main()
6 {
7 char automobile[50];
8 int year;
9 double a_price;
10 double d_price;
11
12 //声明ofstream对象并将其同文件关联起来,若在程序运行前,不存在此文件,则open()将新建一个名为carinfo.txt的文件
13 ofstream outFile;
14 outFile.open("carinfo.txt");
15
16 cout << "Enter the make and model of automobile: ";
17 cin.getline(automobile, 50); //cin.getline:不断读取,直到遇到换行符(少于50个字符),在末尾加上一个空字符,换行符被丢弃
18 cout << "Enter the model year: ";
19 cin >> year;
20 cout << "Enter the original asking price;";
21 cin >> a_price;
22 d_price = 0.913*a_price;
23
24 cout << fixed; //表示用一般的方式输出浮点数,不用科学计数法,比如num=0.00001,cout输出为1e-005,加了fixed后再输出就为0.000010
25 cout.precision(2); //第一位精确,第二位四舍五入,比如num = 318.15,precision(2)为3.2e+02,precision(4)为318.2
26 cout.setf(ios_base::showpoint); //强制显示小数点
27 cout << "Make and model: " << automobile << endl;
28 cout << "Year: " << year << endl;
29 cout << "Was asking $" << a_price << endl;
30 cout << "Now asking $" << d_price << endl;
31
32 outFile << fixed;
33 outFile.precision(2);
34 outFile.setf(ios_base::showpoint);
35 outFile << "Make and model: " << automobile << endl;
36 outFile << "Year: " << year << endl;
37 outFile << "Was asking $" << a_price << endl;
38 outFile << "Now asking $" << d_price << endl;
39
40 outFile.close(); //程序使用完该文件后,应将其关闭。如果忘记关闭,程序正常终止时将自动关闭它
41
42 system("pause");
43 return 0;
44 }
cout.precision(2); 单独表示显示2位有效数字。它前面加上cout << fixed; 则表示显示2位小数。
具体可以看https://blog.csdn.net/weixin_34122810/article/details/85572094
或者 https://blog.csdn.net/nobleman__/article/details/78840105
1 #include<iostream>
2 #include<fstream>//文件I/O
3 #include<cstdlib>//exit()
4 using namespace std;
5 const int SIZE = 90;
6
7 int main()
8 {
9 char filename[SIZE];
10 ifstream inFile;//声明ifstream对象
11 cout << "Enter name of data file:";
12 cin.getline(filename, SIZE);
13 inFile.open(filename);//关联文件
14
15 if (!inFile.is_open())//文件打开失败
16 {
17 cout << "Could not open the file " << filename << endl;
18 exit(EXIT_FAILURE);
19 }
20 double value, sum = 0.0;
21 int count = 0;
22
23 inFile >> value;
24 while (inFile.good())//输入正确
25 {
26 ++count;
27 sum += value;
28 inFile >> value;
29 }
30 if (inFile.eof())
31 cout << "End of file reached." << endl;
32 else if (inFile.fail())
33 cout << "Input terminated by data misamatch." << endl;
34 else
35 cout << "Input terminated for unknown reason." << endl;
36 if (count == 0)
37 cout << "No data processed." << endl;
38 else {
39 cout << "Items read: " << count << endl;
40 cout << "Sum: " << sum << endl;
41 cout << "Average: " << sum / count << endl;
42 }
43 inFile.close();
44
45 system("pause");
46 return 0;
47 }
错误结果:
在文本文件中,输入最后的文本17.5后应该按下回车键,然后再保存文件。以下是正确结果。
[C++ Primer Plus] 第6章、分支语句和逻辑运算符——(一)程序清单
原文:https://www.cnblogs.com/Fionaaa/p/12291072.html