Choose the name of a .txt

I want to open a cmd window that questions (In my language, of course) what name of .txt i want to create, for then put information in it. I have this, but it stills create the txt "Asegurado.txt"

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
 #include <cstdlib>
#include <iostream>
#include <fstream>
#include <conio.h>
#include <string.h>

using namespace std;

main()
{ 
      ofstream entrada;
      
      std:string asegurado;


      cout <<"Nombre a agregar: "; cin>>asegurado;
      entrada.open ("asegurado.txt",ios::out);
      if(entrada.fail() ){
                        cout<<"El archivo no se creo correctamente";
                        getch();
                        }
Last edited on
Simply change:
entrada.open("asegurado.txt", ios::out);
to
entrada.open(asegurado);
Last edited on
First of all, you need to replace "aseguardo.txt" with your variable.
Also, try to declare variable where they are used, don't declare them all at the top of the function. So applying all the recomendations:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <fstream>
#include <iostream>
#include <string>

using namespace std;

int main()
{ 
    string asegurado;
    cout << "Nombre a agregar: ";
    cin >> asegurado;

    ofstream entrada(asegurado);
    if (entrada.fail())
    {
        cout << "El archivo no se creo correctamente" << endl;
    }
}
Last edited on
A lot of thanks! But i still have a problem, when I change entrada.open("asegurado.txt", ios::out); to entrada.open(asegurado) i have the following trouble 13 no matching function for call to `std::basic_ofstream<char, std::char_traits<char> >::basic_ofstream(std::string&)'
Last edited on
To use a std::string in the constructor you need to be compiling using a C++11 compliant compiler. Otherwise you'll need to use the c_str() member function to convert the string to a C-string.

1
2
    ofstream entrada(asegurado.c_str());
    if (!entrada)


Also I recommend just testing the status of the stream instead of using one of the member functions, like fail(), since this tests all the flags.
Topic archived. No new replies allowed.