Massimo D. N. Massimo D. N. - 2 months ago 21
C++ Question

QT creator and ifstream filenam.c_str()

I created a C++ console application with QT creator 4.1.0
This application was originally created wiht Code Blocks and works fine.

this is the code

#include <iostream>
#include <fstream>
#include <string>

using namespace std;

int main()
{
string nomeFile="";

cout << "\nNome file: ";
cin >> nomeFile; // inserire nome file ROF.txt da leggere

//ifstream leggiROF(nomeFile.c_str()); // apre in lettura il file ROF.txt
ifstream leggiROF("C:\\Users\\Massimo Di Natale\\Documents\\Programmi C++ 11\\Programmi_QT\\prova\\a.txt");

string riga="";
if(leggiROF) // se lo trova
{
while(!leggiROF.eof()) // finché non raggiunge la fine del file
{
getline(leggiROF, riga); // legge la riga
cout << "Riga: " << riga << endl;
} // end while
} // end if

else // altrimenti
{
cout << "\nIl nome file inserito non e' stato trovato!!!" << endl;
cout << "Controllare che sia stato inserito nella cartella corretta.\n" << endl;

exit (EXIT_SUCCESS); // termina il programma
} // end else


leggiROF.close();
return 0;
}


if i specify the file name with its path on ifstream it work.
if i want to insert the file name by cin and then use ifstream filenam.c_str() it don't find the file

Answer

Try getline(cin,nomeFile); instead of cin >> nomeFile. Answers at "std::cin.getline( ) vs. std::cin" question describes the difference between them.