【问题标题】:QT creator and ifstream filenam.c_str()QT 创建者和 ifstream filenam.c_str()
【发布时间】:2016-10-06 20:21:17
【问题描述】:

我用 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 filenam.c_str() 它找不到文件。 我想从目录中读取 .txt 文件是项目还是 .exe 是

【问题讨论】:

    标签: c++ qt-creator ifstream qt5.7


    【解决方案1】:

    尝试getline(cin,nomeFile); 而不是cin &gt;&gt; nomeFile。 "std::cin.getline( ) vs. std::cin"问题的答案描述了它们之间的区别。

    【讨论】:

    • 好的,它可以工作,但只包括路径(C:\\Users\\Massimo Di Natale\\Documents\\Programmi C++ 11\\Programmi_QT\\prova\\a.txt),而在代码块中,我只在请求时插入文件名(a.txt)
    • @MassimoD.N.差异可能是由工作文件夹配置引起的。 "a.txt" 文件路径表示ifstream leggiROF("a.txt") 在执行过程中会尝试在工作文件夹中搜索文件。可能在代码块中,您对其进行了特殊配置,或者 "a.txt" 位于可执行文件附近。
    • 我的项目在“文档”文件夹下。 “Documents\Programmi C++ 11\Programmi_OOP\Project name”下的代码块项目,还有我的 a.txt 文件。生成的 .exe 位于“Documents\Programmi C++ 11\Programmi_OOP\Ericsson v2_1\bin\Debug”下。 QT Creator 项目位于“Documents\Programmi C++ 11\Programmi_QT\Project name”下,还有我的 a.txt 文件。生成的 .exe 位于“Documents\Programmi C++ 11\Programmi_QT\build-prova-Desktop_Qt_5_7_0_MinGW_32bit-Debug\debug”下。
    • @MassimoD.N.正如我在文档中看到的,Code Blocks 的默认工作目录是项目目录。 Qt Creator 具有工作目录的另一个默认选项,它是构建结果的目录。因此,在相对路径找到的代码块配置 "a.txt" 和 Qt Creator 配置中找不到它。查看此评论中的链接以获取更多详细信息。
    • 感谢您的帮助。抱歉,但我的英语不太好,所以我不明白如何阅读 Qt Creator 文档。我必须使用这样的东西吗? QDir::setSearchPaths("prova", QStringList("C:\\Users\\Massimo Di Natale\\Documents\\Programmi C++ 11\\Programmi_QT\\prova")); ....它不起作用
    猜你喜欢
    • 2013-08-21
    • 2014-05-25
    • 1970-01-01
    • 1970-01-01
    • 2013-07-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多