Reputation: 2153
I ask for two simple user inputs, a user and a password, I then insert those into a text file, each followed by a semi colon. The semi colons save and the password saves but the username doesn't save for some odd reason.
For example if I input Joe with password 111222444555 it'll
display as ;111222444555;
instead of Joe;111222444555;
Code:
int main()
{
int Number_Of_Attempts = 3;
int result = 0;
char userID[32];
printf("Please enter your user id\n");
scanf("%s", &userID);
char password[12];
printf("The user has not been found. Please enter your a password\n");
scanf("%s", &password);
printf("Username and Password has been saved");
printf("\n");
InsertIntoHash(userID, password);
return 0;
}
void InsertIntoHash(char *userID, char *hash)
{
FILE *fp;
fp = fopen("HashTable.txt", "a");
fprintf(fp, userID);
fprintf(fp,";");
fprintf(fp, hash);
fprintf(fp, ";\n");
fclose(fp);
}
Upvotes: 0
Views: 49
Reputation: 314
You should read in the string using scanf("%31s", userID);
for the userID and scanf("%11s", password);
for the password.
What I think causes the problem is, that you declare and define InsertIntoHash
after the main function, without declaring a prototype at the beginning.
So the code should be the following: (I tested it and it works)
#include <stdio.h>
#include <stdlib.h>
void InsertIntoHash(char *userID, char *hash);
int main() {
int Number_Of_Attempts = 3;
int result = 0;
char userID[32];
printf("Please enter your user id\n");
scanf("%31s", userID);
char password[12];
printf("The user has not been found. Please enter your a password\n");
scanf("%11s", password);
printf("Username and Password has been saved");
printf("\n");
InsertIntoHash(userID, password);
return 0;
}
void InsertIntoHash(char *userID, char *hash) {
FILE *fp;
fp = fopen("HashTable.txt", "a");
fprintf(fp, userID);
fprintf(fp,";");
fprintf(fp, hash);
fprintf(fp, ";\n");
fclose(fp);
}
I hope I could help you! :)
Upvotes: 2
Reputation: 25286
Change scanf("%s", &userID);
to scanf("%s", userID);
as it is already an array which will be passed as a pointer. Same for password.
Use "%11s"
to limit the length read to the size of the buffer, leaving room for the terminating null character.
Upvotes: 1