can i know how to save a file name based on the user's input

for example:

Enter your name : Derrick


then i save this input to a file .txt named derrick (derrick.txt)

how can i do it?

i only know how to use the rename() and delete() function...in the file processing

thank you for your kindness

In C,

#include <stdio.h>

int main(void)
{
   char filename[256], name[] = "Derrick";
   FILE *file;
   sprintf(filename, "%s.txt", name);
   file = fopen(filename, "w");
   if ( file != NULL )
   {
      fprintf(file, "%s\n", name);
      fclose(file);
   }
   return 0;
}

>in c++? is the syntax the same or different?

#include <iostream>
#include <string>

using namespace std

int main()
{
  string name = "Derrick";
  string filename = name + ".txt";
  ofstream file ( filename.c_str() );
  if ( file )
  {
    file<< name <<endl;
  }
}

In file proceesing

how can i find the renamed file....

meaning....i created 2 files named derrick.txt and alex.txt

and in the program when i input derrick, the program will look for the file derrick and open the file,

and if i enter alex, the program will look for alex.txt


thank you

can i know how to save a file name based on the user's input

for example:

Enter your name : Derrick


then i save this input to a file .txt named derrick (derrick.txt)

how can i do it?

i only know how to use the rename() and delete() function...in the file processing

thank you for your kindness

// in c

#include <stdio.h>

int main()
{
    char name[10];
    FILE *filePtr;

    if( ( filePtr = fopen(" myFile.txt ", "w")) == NULL)
    printf("No file found\n");
    else
    {
        printf("Enter name: ");
        scanf("%s",name);
        
        while(!feof(stdin))
        {
             fprintf(filePtr,"%s\n",name);
             scanf("%s",name);
        }
    fclose(filePtr);
    }
    
    getchar();
    
    return 0;
}
Comments
5 years LATE, didn't read the OP wanted C++, posted broken code - triple fail (is the Olympics on?), congrats, you got a nice bronze badge!
This article has been dead for over six months. Start a new discussion instead.