C++: Reading Data and Outputting Data

喜你入骨 提交于 2019-12-25 15:52:13

问题


I'm attempting to write two methods. One, ReadData(istream&) to read in student's ID number, first and last names, 10 program scores, and midterm and exam scores(last two integers) and returns true if all data was read successfully, false otherwise, and one, WriteData(ostream&) to write the data that was read in to a new file in the same order listed above.

I am completely new to file reading and writing so any and all help is much appreciated. The data I am using looks like this...(made up names and scores)

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 

So far I have...

#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();

回答1:


For file reading:

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

Output: just like cout: Like input, you must .open(..) a new file before you can write in it

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



回答2:


Use these for better control (handle could be ReadData or WriteData e.t.c):

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"

Possible way to output data:

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

Another:

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

If the data is in a string you can just do:

WriteData << str;

There is a great tutorial here on c++ and files.



来源:https://stackoverflow.com/questions/18776357/c-reading-data-and-outputting-data

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!