【问题标题】:How to get user input to name a file如何获取用户输入来命名文件
【发布时间】:2020-07-06 18:18:52
【问题描述】:

我一直在尝试如何让用户输入来命名将要创建的文件,我一直在尝试制作一个可以做笔记并将它们存储在文件中的日记应用程序。反正这里是代码

#include "main.h"
#include <string>

char  Start;

int main()
{
    int input;

    std::fstream fFile;

    std::cout << "*******" << std::endl;
    std::cout << "Journal" << std::endl;
    std::cout << "*******" << std::endl;
    std::cout << "Enter any value to continue..." << std::endl;
    std::cin >> Start;
    system("CLS");
    std::cout << "Hello" << std::endl;
    std::cout << "....." << std::endl;
    std::cout << "" << std::endl;

    std::cout << "[1] Create New Note" << std::endl;
    std::cout << "[2] Browse Note Libary" << std::endl;
    std::cin >> input;

    if (input == 1)
    {
        std::string NoteName;
        std::cout << "Enter New Notes Name" << std::endl;
        std::cin >> NoteName;
        fFile.open("NoteName.txt"); // Here is what I can't figure out
        fFile << "test" << std::endl;
        fFile.close;

    }

    if (input == 2)
    {



    }



}

Main.h 只包含 include 并生成它,以便我可以调用 main 函数 (:

【问题讨论】:

  • 只需使用变量NoteName 而不是文本字符串"NoteName.txt",它应该可以工作。只是不要忘记检查该文件是否成功打开,因为它可能不是出于其他原因,包括无效名称。

标签: c++ fstream iostream journal


【解决方案1】:

简单

fFile.open(NoteName);

或者如果您想在用户输入的名称中添加“.txt”

fFile.open(NoteName + ".txt");

您尝试的方式称为字符串插值。它适用于某些语言,但不适用于 C++。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-21
    • 1970-01-01
    • 1970-01-01
    • 2014-07-09
    • 1970-01-01
    相关资源
    最近更新 更多