Search code examples
c++abstract-data-type

File input/output( using classes) in C++


I have a program for an intro CS class of mine and it's the first one I've ever written using classes. Im trying to figure out how to take in user input from a file right now and nothing seems to be working. I tried using getline() and of course infield >> but I was not able to get the users input to output to the screen which of course means the data wasn't retrieved from the file like I'd wish. Here is my code:

#include <string>
#include "bookType.h"
#include <fstream>

using namespace std;

int main(){

bookType book1;
string test;

ifstream inFile; 
inFile.open("testStruct.txt");

getline(inFile, test);

cout << test;

return 0; 
}

here is my text file: MATH SectionTwo

I tested these exact file input commands in a separate file that didn't involve classes, and it worked just fine. What would alter the way infile works simply because im using classes?

I apologize if this is a stupid question. I am a noob.


Solution

  • Is your open succeeding? I think the problem might be that the file stream is not able to open the file (wrong path may be? What happens if you give a fully qualified path "C:\xxx\testStruct.txt").