how to turn a user input into a text file for example user inputs 100 and the program creates a text file named 100.txt?
I have tried to work it out but it still doesnt work properly.
i used

getc(stdin);  

char filename[80];
sprintf(filename,"%d.txt", stdin);

and then i also tried

char line[255];
fgets(line, 255, stdin);
   
char filename[80];
sprintf(filename,"%d.txt", stdin);

any ideas on why it wont create the text file?

This line is incorrect:

sprintf(filename,"%d.txt", stdin);

Since you've already gotten the input from stdin, you should be supplying the variable which contains the user input as an argument instead of stdin .

And since you read it in as a string, you'll want to change "%d" to "%s". Also beware of newlines in your string, which could thoroughly mess up your program.

the program runs, but no output file is generated? am i missing a command still?

char line[255];
fgets(line, 255, stdin);
char filename[80];
sprintf(filename,"%s.txt",line);

Read my last sentance:

Also beware of newlines in your string, which could thoroughly mess up your program.

You're going to have to remove the newline character (if it's there), which is usually as simple as doing the following

if (string[strlen(string)-1] == '\n')
   string[strlen(string)-1] = '\0';

Anyhow, the code works fine for me, even without the newline character removal. So perhaps it would be best for you to show us the code you're using?

well the entirety is only

#include <stdio.h>
#include <string.h>
#include <ctype.h>
int main(int argc, char *argv[]) {
char line[255];
fgets(line, 255, stdin);
char filename[80];
sprintf(filename,"%s.txt",line);
  return 0;
}

the program runs, but no output file is generated? am i missing a command still?

#include <stdio.h>
#include <string.h>
#include <ctype.h>
int main(int argc, char *argv[]) {
char line[255];
fgets(line, 255, stdin);
char filename[80];      // This line can't be here.  It has to 
                        // be above all executable code in C
sprintf(filename,"%s.txt",line);
  return 0;
}

Yeah. Where do you:
1) open the file after you generate the name?
2) write to the file?
3) close the file before exiting?
:?:

well all i want to do is for the user to input a name or number and for the program to create a text file with that name. im not actually writing anything into the file, its just an empty .txt file with a name that hte user chose

You still have to open the file for writing. It doesn't magically get created just because you create a name in a variable...

Look up fopen()

well i used

fout = fopen("%s.txt", "w");

but how do i represet "%s.txt" as the user's input?

well i used

fout = fopen("%s.txt", "w");

but how do i represet "%s.txt" as the user's input?

you already posted the answer to that question in your post #5. Just use variable filename

sprintf(filename,"%s.txt",line); // <<< from your previous post
fout = fopen(filename, "w");

but i though the entry in fopen has to be a either in "" or predefined?

#include <stdio.h>
#include <string.h>
#include <ctype.h>
#define INFILE "questions.txt"


int main(int argc, char *argv[]) {
        char mc;
        char rt;
        char filename[80];
        char line[255];
 FILE *fin,*fout,*fid;
fin = fopen(INFILE, "r");  


printf("enter student ID:");   
fgets(line, 255, stdin);
sprintf(filename,"%s.txt",line);

fout = fopen(filename, "w");
return 0;
}

but i though the entry in fopen has to be a either in "" or predefined?

It can be, but it can also be a variable, such as I posted. All it is looking for is const char*, doesn't care if it is a char variable or a literal string.

but when i leave it as (filename,'w') and compile and run, the program notes a windows error and closes, and no file is generated

fgets() function leaves the '\n' in the input buffer, so you need to truncate it

printf("enter student ID:");
fgets(line, 255, stdin);
// truncate '\n'
if( line[strlen(line)-1] == '\n')
   line[strlen(line)-1] = '\0';
sprintf(filename,"%s.txt",line);

but i though the entry in fopen has to be a either in "" or predefined?

Why would you think that? ;)

well i used

fout = fopen("%s.txt", "w");

but when i leave it as (filename,'w') and compile and run, the program notes a windows error and closes, and no file is generated

Why did you change "w" to 'w'? Change it back and it will work.

the program runs, but no output file is generated? am i missing a command still?

char line[255];
fgets(line, 255, stdin);
char filename[80];
sprintf(filename,"%s.txt",line);

Here is a program to solve your problems. Make sure you're include files are being properly included.

#include <stdio.h>
#include <string.h>
#define MAXINPUT 100

/* Function used if the user didn't pass program parameter */
void getUserInput(void);
 
/* udtf (user defined text filename) is the global character variable buffer.                                                                                   */
char udtf[MAXINPUT];
 
/* Create a constant character array holding the file extentions - you can change the saved file type simply by changing this initialization                                                                               */
const char fext[] = "txt";
 
/* See below for information regarding the keywords "static" and "inline". This is just a header printed for standard information to the user about the program, including how view usage information
or they'll probably never know how.                                                               */
static inline void _header(void)
{
    puts("UDTF (User Define Text Filename) version 1.0");
    printf("Passed parameters or a prompt will allow a user to create a text file whose \nfilename is specifed by the user using the sprintf function");
    printf("For usage \ninformation pass the -h parameter to the program.\n\n");
}
 
/* This is a static funciton which simply means that only the scope of this program is able to access it. Inline means that the function is expanded where it is called; Note that it is not good practice to use inline functions that contain a massive block of code. This function is for usage information at the users request.                                                       */
static inline void _usage(const char *prog_name)
{
    printf("%s -h Show usage help information\n", prog_name);
    printf("%s filename", prog_name);
}
 
int main(int argc, char *argv[])
{
    /* For the noobs sake, the FILE pointer fp will hold a handle or the address returned after issuing the fopen(...) function and will be used for referrence to the open file - which in this case will just close because you simply specified the user create a text file.      */
    FILE *fp;
 
    /* Show program header - refer above for an explaination */
    _header(); 
 
    /* Check to see if the user passed any program parameters so we can use it instead of prompting  the user for a name. Essentially, the argc variable holds the number of parameters passed to the program including the program name itself, which is why its argc > 1 rather than argc > 0.    */
    if (argc > 1)
    {

        /* Check if the user requests usage information */
        if (!strcmp(argv[1], "-h"))
        {

            /* The program name is pointed to by argv[0] - the first element of the array */
            _usage(argv[0]);
            goto End;
        }
 
        /* So if the user passed a program paremeter which'll represent the name of the text file so we don't have to prompt the user, we first make sure the string length of the first parameter char array pointed to by argv[1] doesn't exceed the MAXINPUT constant defined above.
You can change the max input simply by changing the value assigned to the MAXINPUT constant (i.e #define MAXINPUT 80)                                                                   */

        if (strlen(argv[1]) > MAXINPUT) {
   
            /* If the string legnth exceeds MAXINPUT prompt the user */
            getUserInput();
        }
        else
 
            /* Copy the string pointed to by argv[1] into the udtf buffer */
            strcpy(udtf, argv[1]);
    }
    else
        /* If no parameters were passed prompt the user */
        getUserInput();
 
   sprintf(udtf, "%s.%s", udtf, fext);
   /* Attempt to open file use the filename now stored in the udtf buffer and show error if unsuccessful.                                                                         */
    if ((fp = fopen(udtf, "r+")) == NULL) {
        printf("Error: unable to open file %s", udtf);
        return 1;
    }
 
    fclose(fp); /* Close the file */
 
    /* You really shouldn't use goto's they're gay but what-the-hell */
    End:
 return 0;
}
 
/* This function will be used to prompt the user and get the file name via stdin */
void getUserInput(void)
{
    char cinc;
    int a = 0;
    
    printf("Filename: ");
 
    /* While loop getting character by character off stdin using the increment counter a into the global udtf buffer. If you're not aware of what a global variable is, it is a variable that is accessible to all code within the scope of that program. If when the enter key is pressed
or a == MAXINPUT then we want to break the loop and move on.                              */
    while ((cinc = getc(stdin)) != '\n')
    {
        if (a == MAXINPUT)
            break;
        udtf[a] = cinc;
        a++;
    }

    /* Before we return add a end-of-string character so we don't print out garabage. */
    udtf[a]= '\0';
}
/* You really shouldn't use goto's they're gay but what-the-hell */
    End:

"Practice what you preach."
If you
1) know you shouldn't use them,
2) then say you shouldn't use them,
3) and do it anyway,
what are you teaching the people that are new to the language? It's confusing because for them, the code is now useless. They don't understand enough to know what to ignore and what is good... FYI... ;)

commented: Good points... +6

"Practice what you preach."
what are you teaching the people that are new to the language? It's confusing because for them, the code is now useless. They don't understand enough to know what to ignore and what is good... FYI... ;)

I think you should speak for yourself buddy. The code isn't useless BECAUSE of the comments. The reason why I used a goto statement is because it is very intuitive and thus would be easier for a begginer to understand. However, I just wanted to imply that using the goto statement is usually not good depending on the application and/or specifications of a software project - which they're not quite up to, yet, but it is good to keep this in mind becuase instructors discourage its use. I do understand what you say by it might be confusing but even a newbie will know how to distinguish comments from actual code, so, therefore, it is less confusing and more informative - which is what comments are for, right. Last, when you wrote, and I quote, "the code is now useless", well, that just your opinion; one opinion. An absolute newbie, if truely curious, could just google the keyword goto and it'll give a brief, easy-to-understand description of it. So I suppose you're a newbie?!?!

LamaBot

Also, not to be rude, but the code posting was kind of pointless.

  • The code was MAJORLY overcommented.
  • The fix the OP needed was just a matter of one or 2 lines.
  • There was nothing the OP needed to know in your post that hadn't already been shown already.

Oh if you're a newbie and are looking for a very intuitive C/C++ IDE I recommend Code::Blocks if you were not aware. It is absolutely free for download. Here is the link for the download:

http://www.codeblocks.org/downloads.shtml

You'll see a seciton labeled "Code::Blocks IDE (Windows Binaries)", and if you're using Windows, you'll click the "Code::Blocks IDE with MINGW Compiler" if you need too. Good luck my fellow Daniweb friends

LamaBot

The reason why I used a goto statement is because it is very intuitive and thus would be easier for a begginer to understand.

Newbies should generally not use goto statements at all. It's not that they're completely bad; in fact, they can be used in many situations where it can significantly speed up the program or remove the need to use lots of code.

However, gotos are still statements that you have to be careful with. And generally a newbie shouldn't be using them, because they don't know "proper use" of the statement. An expert will know when it's necessary, and will only use it at the right time.

So I suppose you're a newbie?!?!

I can't even comment on this one... :rolleyes:

Also, not to be rude, but the code posting was kind of pointless.

  • The code was MAJORLY overcommented.
  • The fix the OP needed was just a matter of one or 2 lines.
  • There was nothing the OP needed to know in your post that hadn't already been shown already.

It seems you're being defensive which is common. I wrote that program in 3 minutes, not to brag. YOU can say that its majorly over commented but that is just YOUR opinion. Everyone is different. Frankly, you're words are futile and everything you'd said so far indicates that you're a newbie yourself. I guess I could of held back on the comments... and let the newbie try to understand just by reading the code, yes, I could of done that. ;) I'm not here for debates, I'm here to help the begginners. I was a begginner once, everyone is, and I got help from online forums and etc. Let me state the obvious once more, the code I wrote was a C-O-N-T-R-I-B-U-T-I-O-N and the originator of this thread, or anyone who reads it, can take it or leave it. I just hope it'll give someone some incentive or 'flip on the light' for new ideas derived in anyway from that program. FYI, I've seen many debates on usage of comments, just like the one you seem like you want to start and I've realized that if you're a programmer for some buisness writing a library or an individual learning, you've got to consider the circumstances. If you're a senior programmer for a buisness and the buisness regulates comment usage in source code then it is ok, but if you're a newbie, therefore probably not working for a buisness, yet, or just in school, comments support and sometimes facilitate the learning experience. Anyway I hope I've helped out a little my fellow Daniweb friends.

LamaBot

Newbies should generally not use goto statements at all. It's not that they're completely bad; in fact, they can be used in many situations where it can significantly speed up the program or remove the need to use lots of code.

However, gotos are still statements that you have to be careful with. And generally a newbie shouldn't be using them, because they don't know "proper use" of the statement. An expert will know when it's necessary, and will only use it at the right time.

That is weird, you've inadvertentely called many of my past programming instructors thier teaching methods are skewed. Hmm.... I guess you're one hell of a teacher then huh. Of course goto statements are speedy, they essentially change the address of the instruction register to that of the label. I do agree that it takes an expert to know when it is necessary or the right time, trust me, I've seen some buggy code. Nevertheless, goto statements are OK for a newbie to learn first because it is, as I said before, easy to understand and intuitive. I figured they'd eventually learn that it is generally not good programming practice to use them unless you know what you're doing - which is why I add that comment you were so bothered about.

LamaBot

It seems you're being defensive which is common.

If you'll look back on the post that I wrote about your code, it was actually quite near the time that you posted yours. I wrote my post as you were writing yours; so I was not being defensive in the least.

I wrote that program in 3 minutes, not to brag. YOU can say that its majorly over commented but that is just YOUR opinion.

I never said you were trying to brag. And I do realize that this is simply my opinion (I was a bit harsh, sorry), and everyone shares different viewpoints.

Frankly, you're words are futile and everything you'd said so far indicates that you're a newbie yourself.

Meaning which words? My viewpoint on comments? An opinion does not make you a newbie, and I never called you a newbie based on my disagreeing opinion with you. Essentially everyone must learn to accept different viewpoints, or else we'd constantly be having a civil war. ;)

Let me state the obvious once more, the code I wrote was a C-O-N-T-R-I-B-U-T-I-O-N and the originator of this thread, or anyone who reads it, can take it or leave it.

I understand that. Thanks for posting it.

However, my main point was that the problem had almost been solved. It was just a matter of using double quotes instead of single quotes, and using the correct variable.

By posting the entire code, the OP has to read all the comments and the code, which is tremendously long. I'm not saying that this is a totally incorrect thing to do, but it might be easier if you could simplify your code a bit? Adding lots of comments does not necessarily make code easy to understand.

I just hope it'll give someone some incentive or 'flip on the light' for new ideas derived in anyway from that program.

I appreciate and applaud your insight on posting this.

That is weird, you've inadvertentely called many of my past programming instructors thier teaching methods are skewed.

Not surprising; there are many instructors who teach skewed coding methods. Don't get me wrong, I'm not trying to bash your teachers. It all depends on the problem.

In this example, it would be simply easier just to return from main. There's no need to jump to the end of the program with a goto statement. Or you could simply use an if() statement, which although might complicate the program a little; the complexity could be reduced by splitting the various snippets of code into functions, which are then called from the main() function.


I appreciate and applaud your insight on posting this.


Not surprising; there are many instructors who teach skewed coding methods. Don't get me wrong, I'm not trying to bash your teachers. It all depends on the problem.

In this example, it would be simply easier just to return from main. There's no need to jump to the end of the program with a goto statement. Or you could simply use an if() statement, which although might complicate the program a little; the complexity could be reduced by splitting the various snippets of code into functions, which are then called from the main() function.

I can respect that. And I'm sorry if I was subletly harsh too. :lol: I guess I should consider your view point. I'm sorry for implying you were a newbie. Overall, I guess I can appreciate and applause your insight and opinion as well. Basically confirming what I'd said, many teachers do have skewed teaching methods but depends on the problem or circumstances, in essence. It was necessary, however, for me to give all the code or else it'd truely be useless, at least to a newbie :lol: You're forgetting that even a newbie can Copy-and-paste the code into his or her IDE Window. He or she can cut or delete comments thereof. The format looks like crap because of the limited horizontal character space. You should of seen it when I just let one line wrap to another, it look confusing! :sad: For pete's sake, I'll say it again, I wrote that program in response to the originator of this thread in like three minutes. Yes I could of just return from main instead of jumping to the end. My view point obviously differs from yours so I put the goto statement in there for a reason :surprised Also I could of used some if statements among other ways, and used more functions but I figured for a newbie it'd better be as simple as possible. For my last post, I'll give the code without the comments.

The code:

#include <stdio.h>
#include <string.h>
 
#define MAXINPUT 100

void getUserInput(void);
 
char udtf[MAXINPUT];
 
const char fext[] = "txt";

static inline void _header(void)
{

    puts("UDTF (User Define Text Filename) version 1.0");

    printf("Passed parameters or a prompt will allow a user to create a text file whose \nfilename is specifed by the user using the sprintf function");

    printf("For usage \ninformation pass the -h parameter to the program.\n\n");

}

static inline void _usage(const char *prog_name)
{

    printf("%s -h Show usage help information\n", prog_name);
    printf("%s filename", prog_name);

}
 
int main(int argc, char *argv[])
{
  
    FILE *fp;
 
    _header(); 

    if (argc > 1)
    {

        if (!strcmp(argv[1], "-h"))
        {

            _usage(argv[0]);
            goto End;

        }

        if (strlen(argv[1]) > MAXINPUT)
            getUserInput();
        else
            strcpy(udtf, argv[1]);
 
    }
    else
        getUserInput();
 
   sprintf(udtf, "%s.%s", udtf, fext);
 
    if ((fp = fopen(udtf, "r+")) == NULL) 
    {

        printf("Error: unable to open file %s", udtf);
        return 1;

    }
 
    fclose(fp); 
 
    End:
    return 0;
}

void getUserInput(void)
{
    char cinc;
    int a = 0;

    while ((cinc = getc(stdin)) != '\n')
    {

        if (a == MAXINPUT)
            break;
 
        udtf[a] = cinc;
        a++;

    }

    udtf[a]= '\0';
}

That is very basic programming and no new concept incorporated.

LamaBot

You forgot the code tags. ;)

One trick if you've got comment-heavy code is to use DaniWeb's built-in code coloring tags, or [code=cplusplus]. It can work wonders.[code=c] or . It can work wonders.[code=cplusplus]. It can work wonders.

You forgot the code tags. ;)

One trick if you've got comment-heavy code is to use DaniWeb's built-in code coloring tags. It can work wonders.

I know, I'm just as lazy on Actionscript.org :o I'll make sure I use them from now on as I should. Thanks buddy. :)

/* This function will be used to prompt the user and get the file name via stdin */
void getUserInput(void)
{
    char cinc;
    int a = 0;

/* 
While loop getting character by character off stdin using the 
increment counter a into the global udtf buffer. If you're not aware of what a global variable is, it is a variable that is accessible to all code within the scope of that program. If when the enter key is pressed
or a == MAXINPUT then we want to break the loop and move on.
*/
    while ((cinc = getc(stdin)) != '\n')
    {
        if (a == MAXINPUT)
            break;
        udtf[a] = cinc;
        a++;
    }

/* Before we return add a end-of-string character so we don't print out garbage. */

    udtf[a]= '\0';
}

Hey it looks good for once! Hope I've helped my fellow Daniweb friends.

LamaBot

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.