首页 > 解决方案 > 在字符串上使用 += 运算符以添加 .txt 用于文件输出

问题描述

我目前正在上大学的第一个 CompSci 课程,我的一个作业要求我输入一个名称,然后使用该名称创建一个具有相同名称但末尾带有“.txt”的文件。

它打印出它应该命名的内容,但我在尝试输入的名称下找不到任何文件。

有谁知道出了什么问题?

#include<iostream>
#include<fstream>
#include<iomanip>
#include<math.h>

using namespace std;

int main()
{
    string des_name;
    string ship_name;
    float ship_mass;
    float e_thrust;

    const float g0 = 9.8;

    cout << "Designer name: " << endl;
    getline(cin , des_name);

    cout << "Ship Name: " << endl;
    cin >> ship_name;
    ship_name += ".txt";

    cout << "Ship Mass: " << endl;
    cin >> ship_mass;

    cout << "Engine Thrust: " << endl;
    cin >> e_thrust;

    cout << "File written for " << ship_name;

    ofstream output_file;
    output_file.open(des_name.c_str());
    output_file << "##########" << ship_name << "##########" << endl << endl;
    output_file << "Designed by: " << setw(10) << des_name;
}

标签: c++

解决方案


嗯,您打开一个基于 的文件des_name,但它ship_name是您附加.txt到的:

ship_name += ".txt";
:
output_file.open(des_name.c_str());

我会把这个异常作为一个起点:-)


推荐阅读