Start New Discussion within our Software Development Community

I am making a program that reads from a .txt file and outputs the names that are in my .txt file into an output file that the user specifies. My program compiles but then I get an error that says

"int main(): Assertion `fin.is_open()' failed.
Aborted"

What am I doing wrong

#include <iostream>
#include <fstream>
#include <string>
#include <cassert>
#include <cfloat>
using namespace std;

int main()
{
 cout << "Enter the name of the input file:";
 string inputname;
 getline(cin, inputname);
 ifstream fin;
 fin.open(inputname.data());
 assert ( fin.is_open() );
 int count=0;
 double reading,
 sum=0.0;

 for(;;)
  {
    fin >> reading;
    if (fin.eof()) break;
    count++;
  }
 fin.close();

 cout << "Enter name of output file:";
 string outputname;
 getline(cin, outputname);
 ofstream fout(outputname.data());
 assert(fout.is_open());
 fout << "There are " << count << " numbers.";

 fout.close();
 cout << "Finished!\n";
}

This is from http://www.cplusplus.com/reference/string/string/data/ about string::data:
Get string data

Returns a pointer to an array of characters with the same content as the string.

Notice that no terminating null character is appended (see member c_str for such a functionality).

So modify your code something like this:

cout << "Enter the name of the input file:";
 string inputname;
 getline(cin, inputname);
 ifstream fin;
 fin.open(inputname.c_str()); //use c_str() instead of data
.
.
.
.
.
.
 ofstream fout(outputname.c_str()); //use c_str() instead of data
.
This article has been dead for over six months. Start a new discussion instead.