QT创建者和ifstream filename .c_str()

QT creator and ifstream filenam.c_str()

本文关键字:str filename 创建者 ifstream QT      更新时间:2023-10-16

我用QT creator 4.1.0创建了一个c++控制台应用程序这个应用程序最初是用代码块创建的,工作得很好。

这是代码

#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;
}

如果我在ifstream上指定文件名和它的路径,它会工作。如果我想通过cin插入文件名,然后使用ifstream filename .c_str(),它找不到文件。我想从项目目录或。exe目录中读取。txt文件

尝试getline(cin,nomeFile);代替cin >> nomeFile。在"std::cin"处回答。Getline()与std::cin"问题描述了它们之间的区别