【问题标题】:C++: Reading Data and Outputting DataC++:读取数据和输出数据
【发布时间】:2013-09-17 13:17:09
【问题描述】:

我正在尝试编写两种方法。一、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();

【问题讨论】:

标签: c++ ostream istream


【解决方案1】:

文件读取:

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

输出:就像cout: 和输入一样,你必须.open(..)一个新文件才能写进去

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

【讨论】:

    【解决方案2】:

    使用这些以获得更好的控制(句柄可以是 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;
    

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-06-12
      • 2016-02-02
      • 1970-01-01
      • 2016-05-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多