For one reason or another, I can not get two instances of fgets()
and strcat()
to work.
This is my code:
#include <stdio.h>
#include <string.h>
int main()
{
char str[150];
char userName[8]; char password[8];
printf("Enter username: ");fgets(userName, 9, stdin);
printf("Enter password: ");scanf("%s", password);
strcpy(str, "INSERT INTO USERS (ID,USERNAME,PASSWORD,IP) " \
"VALUES (1, '");
strcat(str, userName);
strcat(str, "', '");
strcat(str, password);
strcat(str, "', '120.132.12.1');");
puts(str);
return 0;
}
When getting the string for "password", I can not use fgets()
or it throws the error "Abort trap: 6". Specifically I am using:
fgets(password, 9, stdin);
9 elements because I read you need to account for the null terminating char in your total.
I don't understand this because being that there are as many elements in the char array as userName, I thought the code to get the string should be virtually the same other than the char array name.
Also, strcat()
seems to not be working when trying to append "str" with userName. My output looks something like this:
Enter username: beckah12
Enter password: beckah12
INSERT INTO USERS (ID,USERNAME,PASSWORD,IP) VALUES (1, '', 'beckah12', '120.132.12.1')
Why is it skipping over the "strcpy(str, userName)"
?
There is some memory overlap when I declare these two strings. When I declared a random integer between the two strings, it took retained the input for both. How do I fix this memory overlap with a more permanent solution?
For your fgets()
you correctly stated:
9 elements because I read you need to account for the null terminating char in your total.
But in your variable declarations you forgot it:
char userName[8]; char password[8];
Make them char ....[9]
and your program shouldn't abort any more.
But, as @chux mentioned:
if you read complete lines of text you will also have to deal with the new line character, which makes your code something like that:
char userName[10]; char password[10];
...
fgets( userName, sizeof userName, stdin );
if( userName[strlen(userName)-1] == '\n' ) {
//truncate new line character
userName[strlen(userName)-1] = '\0';
}
... and still you will have a problem if someone types a name or a password of more than 8 characters. So I would suggest:
#define L_USER 8
char userName[256]; char password[256];
...
fgets( userName, sizeof userName, stdin );
if( strlen(userName) > L_USER ) {
//truncate name if too long
userName[L_USER] = '\0';
}
if( userName[strlen(userName)-1] == '\n' ) {
//truncate new line character
userName[strlen(userName)-1] = '\0';
}