0

I'm currently working on this program for a class in my university. I've tried multiple approach with no success. I'm pretty sure it's just a conversion problem, but I want to understand the differences.

What the program supposed to do : We're to create a program that ask the user for two filenames. One will be an input and another will be an output. The program is supposed to read the input and write the line to the output while until the end of the input file is not reached.

My Code :

#include <iostream>
#include <fstream> //included for read/writing files
#include <string> //Included this for getline to read the file

using namespace std;

int main() {

    ifstream infile; // Stream to read from input file
    ofstream outfile; // Stream to write to output file
    char inputfilename[80], outputfilename[80]; //declaring two character arrays to save the file names.
    string text;

    cout << "What is the name of your input file (text.txt)" ; // Prompting user for input file name
    cin >> (inputfilename); // Getting input file
    infile.open(inputfilename, ios::in); // Opening the input file.
    cout << "What is the name of your output file" ; // Prompting user for output file name
    cin >> (outputfilename);
    outfile.open(outputfilename, ios::out);
    if(!infile) { // If cannot open file 

        cout << "There was an error opening your file!" ;
        return 1; 

    }
    if (!outfile) {

        cout << "There was an error opening your file!" ;
        return 1; 

    }
    while (infile.eof()==0) {

        fgets(text, 80, infile);
        fprintf(outfile,"%d.  %s\n", text);

    }

    infile.close();  // Closing input file
    outfile.close(); // Closing output file

    return 0;
}

What I've tried : I didn't know if it was being affected by how I opened the file. I previously tried.

    ifstream infile;
    ofstream outfile;
    char text, inputfilename[80], outputfilename[80]; <----- 1
    cout << "What is the name of your input file (text.txt)" ;
    gets(inputfilename); <----- 2
    infile.open(inputfilename);
    cout << "What is the name of your output file" ;
    gets(outputfilename); <----- 2
    outfile.open(outputfilename);

1) I switched char I previous tried

char text 
char text[80]
char *text[80]

2) Would switching how getting the file name change anything in the while loop(I previous tried getline and gets)? Additionally the "f" in front of fgets/fprints/etc are always associated with a file stream?

Note: My teacher gave us the hint.

"Suppose you read a line from the input file into a string variable called str using the following statement: fgets(str, 80, infile);You can add a line number and save the line with the line number to the output file using the same statement using: fprintf(outfile,"%d. %s\n",Next_line_number++, str);"

from this I tried :

while (infile.eof()==0) {

        fgets(text, 80, infile);
        fprintf(outfile,"%d.  %s\n", text);

    }

as well as

while (infile.eof()==0) {
        fgets(text, 80, infile);
        fputs(text, outFile);

}

and

while (infile.eof()==0) {
        getline(infile, text);
        fprintf(outfile,"%d.  %s\n", text);

    }

I also tried making a long and using that to increment the line number. I'm fairly new to programming; if any of the methods I'm using our dated please let me know (on some sites they were saying fgets is dated and not supported on cx11 or some version of C++)! I want to understand the concepts vs just get the programming running. Should note Lines 34-35 are where my code is always erroring out and it's

cannot convert 'std::__cxx11::string {aka std::__cxx11::basic_string}' to 'char*' for argument '1' to 'char* fgets(char*, int, FILE*)'

I figured I was getting this because it has a pointer to the file and I'm asking the user vs having the file declared in the program. This is causing a conversion that causing my error.

halfer
  • 19,824
  • 17
  • 99
  • 186
Froxty
  • 5
  • 3

1 Answers1

1
fgets(text, 80, infile);

fgets() is a C library function, that expects a char * as its first parameter. It knows absolutely nothing about any C++ class, and not just std::string that you are passing as the first parameter. Neither does fgets() has any clue about the C++ std::ifstream class you're attempting to pass to it as its third parameter. And that's exactly what your compiler's error message states.

You are randomly mixing up C and C++ code, which results in repeated confusion.

char inputfilename[80], outputfilename[80];

You should also use std::strings, instead of arbitrary-sized C style arrays, here.

while (infile.eof()==0) {

This is always a bug, and read this linked article for more information.

fprintf(outfile,"%d.  %s\n", text);

Again: fprintf is also a C library function, that knows absolutely nothing about C++ classes like std::string and std::ofstream. In either case, this is a bug because this string has placeholders for two parameters, an integer, %d, and C style string, %s; and you're giving just one parameter here, text. In the event that you were writing C instead of C++ code, this would not've worked either, but that's mostly academic. This is a C++ program, and this C library function has no business doing anything here, in the first place.

When you are reading from a std::ifstream:

  • You can use std::getline to read an entire line of text into a std::string

  • Alternatively you can use the >> formatted extraction operator

  • Or you can use various methods of the std::ifstream object to read from the file and into a suitable buffer

These alternatives are not equivalent (otherwise what would be the point?) and they do different things, and the right one to use depends on what the requirements are.

Similarly, to write to a std::ofstream you can use:

  • The << formatted output operator.

  • Various methods of the std::ofstream object itself.

And, in some advanced situations you can take advantage of the iterator library, and implement reading and writing using input and output iterators, too.

The correct approach depends on the individual situation. For more information on how to read and write from files in C++ using these approaches, see any good C++ book. Whichever C++ book actually advised you to use fgets() to read from a std::ifstream and into a std::string: throw it away, and get a better book, from the list linked above. If this is just what you found in some program somewhere on the Internet -- you can't learn C++ this way, by piecing together different parts of different programs, and hope that the results work. To fix all of your compilation errors: remove all that C code that knows absolutely nothing about C++, and replace it with proper C++ code, using any of the options I outlined above, using the examples from the C++ books linked above, as a reference.

Sam Varshavchik
  • 114,536
  • 5
  • 94
  • 148
  • _"This is always a bug"_ Well, no. Usually/often. Not always. – Lightness Races in Orbit Mar 18 '19 at 00:37
  • Let me just start by saying thanks! I'm really glad you responded. I've started using c++ on CodeAcademy/Watching Videos and taking notes. I would use http://www.cplusplus.com and follow tutorials as well ,but I noticed I'm doing myself a disservice by not getting a textbook(now I can get a good one!). I would look up individual programs/or sites on how to read/write for smaller parts.(For Instance, first I looked up how to ask user for file input. Then I would look up how to read/write using fstream and try to piece it all together). This led to this confusion. Thanks again, for all the help! – Froxty Mar 18 '19 at 01:27
  • O and Thanks I actually had this in a previous attempt, but fixed to while (!infile.eof()) – Froxty Mar 18 '19 at 01:28
  • You cannot learn C++ by reading a web site. Any joker can put together any web site that says anything that the clown who owns it want to say. I have a web site. It costs me $11 a month. It would cost me a lot more than that to publish a book. It costs money to grow, cut down, and harvest dead trees, truck them to a paper manufacturing plant, then a printing plant, then bookstores all over the world. A book publisher will make sure than a C++ book will be of high quality before risking publishing it. No such cost of entry is required to put up a web site. – Sam Varshavchik Mar 18 '19 at 01:57