Disclaimer: this question is directly related to my programming homework.
My C++ assignment consists of opening a .txt file, performing a bunch of operations on it, and then saving the .txt file. Problem is, I’m having a hard time just grasping the basic concepts of reading and writing files.
My code:
#include <iostream>
#include <fstream>
using namespace std;
int main () {
ifstream inData;
ofstream outData;
// is it necessary to open datalist.txt for both the in and out streams?
inData.open ("datalist.txt");
outData.open("datalist.txt");
if (inData.is_open()) {
cout << "yay, i opened it\n"; // this outputs as expected
char fileData[100]; // have to use char arrays as per instructor. no strings
inData >> fileData; // store text from datalist.txt in fileData char array
cout << fileData; // nothing happens here... why?
outData << "changing file text cause I can"; // this works just fine.
}
else {
cout << "boo, i couldn't open it";
}
inData.close();
outData.close();
return 0;
}
The main issue I’m encountering is that I don’t understand how to read the data in a file at even a basic level, let alone parse the file into relevant information (the purpose of the program is to read, write, and manipulate information in a semi-colon delimited list).
In addition to this question, I also am a little confused on two other things. First, is it necessary to open datalist.txt for both the in and out streams, for some reason it just feels weird that I have to open the same file twice. Second, my instructor doesn’t want us to use the string class, and instead use char arrays. I don’t understand the logic behind this and was hoping someone could elaborate why (or perhaps give a counter argument to why) strings are bad.
You don’t open a file for reading and writing at the same time. Well, not with two different objects that don’t know about each other at any rate. You either use a std::fstream (which can do simultaneous reading and writing), or you read first, close the file, process the data, then write it.
Also:
I think you may want to get a better instructor. The use of a naked, stack-based
char*array is not something that any C++ teacher worth their salt should endorse.This is where buffer overruns come from.