Hey guys,
Still working on my project for my programming class and I have encountered yet another problem! I have a function that asks the user to enter a drill name. The function will then search to see if the file exists, and if not it will create it. If it does exist, it will prompt the user to enter a different name for the drill.
So here's the code snippet for the creation part of my function:
Code:
printf("To create a drill, please start by entering the following:\n");
do {
/* clears the arrays */
for (i=0; i<SIZE; i++)
drill[0][i]='\0';
for (i=0; i<2; i++)
garbage[i]='\0';
printf("Drill Name:\n");
fgets(garbage, 2, stdin);
fgets(drill[0],50,stdin);
/* removes the newline character */
if (drill[0][strlen(drill[0])-1]=='\n')
drill[0][strlen(drill[0])-1]='\0';
/* adds the .txt to the array */
addtxt(drill, 0);
/* attempts to open the file to see if the user exists */
new_drill = fopen(drill[0], "r");
if (new_drill == 0) {
/* adds the txt file if the drill doesn't exist */
new_drill = fopen(drill[0], "w");
trigger = 1;
} else
printf("Drill already exists! Please enter another name.\n\n");
} while (trigger == 0);
Now my problem is storing the newline character. If the drill doesn't exist, it stores the newline character in garbage just fine, and stores the name in drill. However, if the drill already exists, when it repeats the do statement, it doesn't store a newline character in garbage. So when I enter in a drill (Lets say Push-up), it will store the P in garbage and create the .txt ush-up.txt. So my question is:
Why does is store the newline only on the first time? I don't have this problem in any of my other functions. Also, how can I fix this? I'm a bit confused as to why this doesn't work like it should.
Thanks
-Matt