【问题标题】:use qt c++ set manual location and create file使用 qt c++ 设置手动位置并创建文件
【发布时间】:2013-10-07 10:00:55
【问题描述】:

我刚开始学习c++,一直在尝试设置手动位置来创建文件,但是在这里遇到了一些麻烦。

你有什么办法解决这个问题吗?

int main()
{
    char location;
    std::cin>>location;
    QFile file("location");
    if (!file.open(QIODevice::WriteOnly | QIODevice::Text))
        return 1;
    QTextStream out(&file);
    out << "The magic number is: " << 49 << "\n";
}

【问题讨论】:

  • 根据我的个人经验,先学习 C++,然后开始使用 Qt 框架(如果需要)是一种更简单的方法。 Qt 框架的细节会使学习 C++ 变得更加困难。

标签: c++ qt file


【解决方案1】:

其他答案已经解决了大多数问题。我想指出,您可以使用 Qt 的文本流来访问标准输入和标准输出,只是为了保持所有 Qt。如果您想静态链接您的项目,它有助于提高可执行文件的大小 - 您不需要链接 C++ 流或字符串。

#include <QFile>
#include <QString>
#include <QTextStream>
#include <cstdio>

int main()
{
    QTextStream in(stdin), out(stdout); // the input and output streams, Qt way
    out << "Enter file location: " << flush;
    QString location = in.readLine(); // this should store the file location
    QFile file(location);
    if (!file.open(QIODevice::WriteOnly | QIODevice::Text))
        return 1;
    QTextStream fout(&file);
    fout << "The magic number is: " << 49 << "\n";
    return 0;
}

【讨论】:

    【解决方案2】:

    有几个问题需要解决。

    1. 使用#include 包含必要的头文件
    2. “char”类型变量仅包含一个字符,例如'一种'。您需要使用 std::string 或 QString。
    3. 要使用变量,请勿将其括在引号中。例如使用位置而不是“位置”。
    4. 完成后始终关闭文件。
    5. 确保您的函数始终返回预期值。在这里它应该返回一个整数。

    所以你的代码可以被修复以获得这个:

    #include <string>
    #include <iostream>
    #include <QFile>
    #include <QTextStream>
    
    int main()
    {
        std::string location;
        std::cin >> location;
        QFile file(location.c_str());
        if (!file.open(QIODevice::WriteOnly | QIODevice::Text))
            return 1;
        QTextStream out(&file);
        out << "The magic number is: " << 49 << "\n";
        file.close();
        return 0;
    }
    

    【讨论】:

      【解决方案3】:

      您的变量位置只有一个字符,而不是字符串。 如果你想使用Qt,那么你应该使用它的容器(QString)。 在这里,您尝试使用位置 current_dir/location(“”的原因)创建文件,但不是在您的 var 中存储的位置。

      QFile file("location");
      

      您没有 Qt 需要的 QApplication(或 QConsoleApplication)。 您应该从创建 Qt 应用程序的基础开始。

      【讨论】:

        【解决方案4】:

        我会用以下方式重写你的代码:

        int main()
        {
            std::string location; // this should store the file location
            std::getline(std::cin, location); // read user input for file location
            QFile file(location);
            if (!file.open(QIODevice::WriteOnly | QIODevice::Text))
                return 1;
            QTextStream out(&file);
            out << "The magic number is: " << 49 << "\n";
            return 0;
        }
        

        【讨论】:

          猜你喜欢
          • 2017-06-02
          • 1970-01-01
          • 1970-01-01
          • 2023-03-17
          • 2021-04-04
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多