C++:读取数据和输出数据

C++: Reading Data and Outputting Data

本文关键字:数据 输出 读取 C++      更新时间:2023-10-16

我正在尝试编写两个方法。一个是 ReadData(istream&),用于读取学生的 ID 号、名字和姓氏、10 个课程分数以及期中和考试成绩(最后两个整数),如果所有数据都已成功读取,则返回 true,否则返回 false,另一个是 WriteData(ostream&),用于按上面列出的相同顺序将读入的数据写入新文件。

我对文件阅读和写作完全陌生,因此非常感谢任何和所有帮助。我使用的数据看起来像这样...(编造姓名和乐谱)

10601   ANDRES HYUN 88 91 94 94 89 84 94 84 89 87 89 91 
10611   THU ZECHER 83 79 89 87 88 88 86 81 84 80 89 81 
10622   BEVERLEE WAMPOLE 95 92 91 96 99 97 99 89 94 96 90 97 
10630   TRUMAN SOVIE 68 73 77 76 72 71 72 77 67 68 72 75 

到目前为止,我有...

#include <iostream>
#include <fstream>
#include <string>
using namespace std;
ifstream ReadData;
ReadData.open("filename.txt");
if ReadData... ///Not sure how to make it return true or false 
ReadData.close();
ostream WriteData;
for (k=0,k<101,k++)
//how do you output to a new file from here?
WriteData.close();

对于文件读取:

if(ReadData.is_open()) .... // check if file is open

输出:就像cout一样:与输入一样,您必须先.open(..)一个新文件,然后才能写入其中

ofstream WriteData;
WriteData.open("Output.txt");
WriteData << "Hello World!n"; //Prints Hello World!

使用这些来更好地控制(句柄可以是 ReadData 或 WriteData 等):

if( handle.is_open() ) .. // checks if file is open or closed
if( handle.good() ) .. // checks if stream is ready for input/output 
if( handle.bad() ) .. // checks if read/write operation failed
if( handle.fail() ) .. // same as bad, but catches format error
if( handle.eof() ) .. // returns true if opened file has reached the "end of file"

输出数据的可能方式:

WriteData.write(buffer, size); // char *buffer, int size (of buffer)

另一个:

for(int i = 0; i<size; ++i) WriteData<<buffer[i];

如果数据在字符串中,您可以执行以下操作:

WriteData << str;

这里有一个关于 c++ 和文件的很棒的教程。