0

This file read in some data from AD.txt, stores it to a string, and the writes the string to ADsubjects.txt. My write function seems to work fine but my read is not being called. Its not even going inside the read function to print the cout statements. I assumed that if I just simply place the call function it should appear automatically. Here is my code:

#include <iostream>
    #include<fstream>
    #include <string.h>
    #include<iomanip>
    #include <cstdlib>
    #define rmax 15
    using namespace std;
    string data1;

Read function:

    void readSubjects(){
        cout<<"inside read"<<endl;
        ifstream is;
        is.open("AD.txt"); //opening the file
        cout<<"open text"<<endl;
        while(!is.eof()){
            char line[rmax];
            cout<<line<<endl;
            data1 += "\"";

            is.getline(line,rmax);
            for(int i=0; i<11;i++){
                data1 += line[i];
            }
            data1 += "\" \\ ";
        }
      is.close();
    }

Write function:

    void writeSubjects(){
        ofstream os;
        os.open("ADsubjects.txt",ios::out);
        os<<data1;
        os.close()
    }

Main function:

    int main() {
        readSubjects();
        cout<<"read"<<endl;
        writeSubjects();
        cout<<"written"<<endl;
        cout << "Hello, World!" << endl;
        return 0;
    }
scotthenninger
  • 3,613
  • 1
  • 12
  • 23

2 Answers2

1

In this code; There are many issues.

Compilation Issue in os.close() - Missing semicolon

cout<<line<<endl; code after the char line[rmax]; is wrong as it is not initialized. Printing uninitialized variable may mess up your terminal.

Actually the readline reads the line correctly. Why do you copy 11 characters to data1 from line using a for loop? Max allowed length is 15 in the example. You can just put it as follows.

data1 += line;

Following code will work.

void readSubjects(){
        cout<<"inside read"<<endl;
        ifstream is;
        is.open("AD.txt"); //opening the file
        cout<<"open text"<<endl;
        while(!is.eof()){
            char line[rmax];
//            cout<<line<<endl; // This is wrong
            data1 += "\"";

            is.getline(line,rmax);

 //           for(int i=0; i<11;i++){
 //               data1 += line[i];
 //           }

            data1 += line;

            data1 += "\" \\ ";
        }
      is.close();
    }
Sujith Gunawardhane
  • 1,095
  • 7
  • 19
0

In the while loop for the read, all you need to do is:

    while(is){  //the is will run until it hits the end of file.
      //code here
    }  

if readSubjects() isn't getting called at all, then perhaps the function prototype needs to be declared above int main() and the actual function declaration should be declared below int main(), something like this:

    void readSubjects();


    int main(){
      readsubjects();
      //more code...
    }


    void readSubjects()
    {
      //actual function code
    }
timtoy1
  • 31
  • 5