Member Avatar for kohkohkoh

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?

>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;
  }
}
Member Avatar for kohkohkoh

ops sorry...is it C++

thanks for the help

Member Avatar for kohkohkoh

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;
}
commented: 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! -4
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.