C++:读取数据和输出数据
C++: Reading Data and Outputting Data
我正在尝试编写两个方法。一个是 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++ 和文件的很棒的教程。
相关文章:
- 更改.cpp程序的输入文件中数据的位置会意外更改输出
- 使用 python 或 c ++ 中的 sql 根据输入数据输出输出示例
- 尝试从 txt 文件中读取两条数据并输出它们 [C++]
- 将多个效果与 libSox 链接并读取输出数据的正确方法
- 如何将函数的输出数据存储在文本文件中
- 如何从amd gpus的显示输出中获取图像数据
- 自定义堆栈上 std::string 数据的输出
- 如何从文本文件输出数据?(学生成绩单计划)
- 为什么我的数据/输出文件为空?
- C++:如何将数据输出到多个.dat文件
- C++:将存储在List容器中的数据输出到文本文件中
- .wav C++数据输出不正确
- C++:模拟餐饮公司计费程序-无法将错误数据输出到错误文件
- 使用iomanip将数据输出格式化为具有Qt的文本文件
- matPutVariable:尝试将数据输出到mat文件时出错(matrix::serialize::WrongSize
- 如何使用类似于gcc-xml的clang生成元数据输出
- 如何使用Python从UART Beaglebone获取数据输出
- GP635T gps传感器的数据输出
- 如何在Windows控制台中将数据输出到自定义流(3>4>等)?
- 流数据输出问题