C++流与文件操作详解
立即解锁
发布时间: 2025-08-19 01:36:34 阅读量: 1 订阅数: 6 


C++面向对象编程入门与实践
# C++ 流与文件操作详解
## 1. 输入验证与错误处理
在进行输入操作时,我们常常需要对输入的数据进行验证,确保其符合特定的范围要求。例如,在输入英寸值时,我们希望该值大于 0 且小于 12.0。以下是实现该验证的代码:
```cpp
while(true) //cycle until inches are right
{
cout << "Enter inches: ";
cin.unsetf(ios::skipws); //do not skip white space
cin >> inches; //get inches (type float)
if(inches>=12.0 || inches<0.0)
{
cout << "Inches must be between 0.0 and 11.99\n";
cin.clear(ios::failbit); //”artificially” set fail bit
}
if( cin.good() ) //check for cin failure
{ //(most commonly a non-digit)
cin.ignore(10, '\n'); //eat the newline
break; //input is OK, exit ‘while’
}
cin.clear(); //error; clear the error state
cin.ignore(10, '\n'); //eat chars, including newline
cout << "Incorrect inches input\n"; //start again
} //end while inches
```
上述代码的执行流程如下:
1. 进入无限循环,提示用户输入英寸值。
2. 取消跳过空白字符的设置,读取用户输入的英寸值。
3. 检查输入的英寸值是否在 0.0 到 11.99 之间,如果不在此范围内,设置 `failbit` 标志。
4. 使用 `cin.good()` 检查输入是否成功,如果成功则忽略换行符并跳出循环。
5. 如果输入失败,清除错误状态,忽略输入的字符,提示用户重新输入。
同时,我们还可以对输入的英尺值进行验证,确保其为正确的整数且在 -999.0 到 999.0 之间。以下是验证英尺值的函数:
```cpp
int isFeet(string str) //return true if the string
{ // is a correct feet value
int slen = str.size(); //get length
if(slen==0 || slen > 5) //if no input, or too long
return 0; //not an int
for(int j=0; j<slen; j++) //check each character
//if not digit or minus
if( (str[j] < '0' || str[j] > '9') && str[j] != '-' )
return 0; //string is not correct feet
double n = atof( str.c_str() ); //convert to double
if( n<-999.0 || n>999.0 ) //is it out of range?
return 0; //if so, not correct feet
return 1; //it is correct feet
}
```
### 主程序示例
```cpp
int main()
{
Distance d; //make a Distance object
char ans;
do
{
d.getdist(); //get its value from user
cout << "\nDistance = ";
d.showdist(); //display it
cout << "\nDo another (y/n)? ";
cin >> ans;
cin.ignore(10, '\n'); //eat chars, including newline
} while(ans != 'n'); //cycle until ‘n’
return 0;
}
```
主程序的执行流程如下:
1. 创建一个 `Distance` 对象。
2. 进入循环,获取用户输入的距离值并显示。
3. 询问用户是否继续,如果用户输入 `n` 则退出循环。
## 2. 磁盘文件 I/O 流
大多数程序都需要将数据保存到磁盘文件中,并在需要时读取回来。在 C++ 中,我们可以使用 `ifstream`、`fstream` 和 `ofstream` 类来进行磁盘文件的输入和输出操作。这些类的继承关系如下:
```mermaid
graph TD;
ios --> istream;
ios --> ostream;
istream --> ifstream;
ostream --> ofstream;
istream --> iostream;
ostream --> iostream;
iostream --> fstream;
fstreambase --> ifstream;
fstreambase --> fstream;
fstreambase --> ofstream;
streambuf --> filebuf;
filebuf --> fstreambase;
```
### 2.1 格式化文件 I/O
#### 2.1.1 写入数据
格式化 I/O 中,数字以字符序列的形式存储在磁盘上。以下是一个将字符、整数、双精度浮点数和字符串对象写入磁盘文件的示例程序:
```cpp
// formato.cpp
// writes formatted output to a file, using <<
#include <fstream> //for file I/O
#include <iostream>
#include <string>
using namespace std;
int main()
{
char ch = 'x';
int j = 77;
double d = 6.02;
string str1 = "Kafka"; //strings without
string str2 = "Proust"; // embedded spaces
ofstream outfile("fdata.txt"); //create ofstream object
outfile << ch //insert (write) data
<< j
<< ' ' //needs space between numbers
<< d
<< str1
<< ' ' //needs spaces between strings
<< str2;
cout << "File written\n";
return 0;
}
```
上述代码的执行步骤如下:
1. 定义要写入的字符、
0
0
复制全文
相关推荐








