The problem is that fgets
also reads \n
and stores it in the buffer read. You can resolve this by manually removing the \n
which was the last read:
fgets(username, 25, stdin);
size_t ultima_pos = strlen(username) - 1;
if (username[ultima_pos] == '\n'){
username[ultima_pos] = 'void ler_string(char *destino, size_t tamanho){
fgets(destino, tamanho, stdin);
size_t ultima_pos = strlen(destino) - 1;
if (destino[ultima_pos] == '\n'){
destino[ultima_pos] = 'ler_string(username, 25);
';
}
}
'; //terminar a string no local onde está o '\n'
}
In order not to have to repeat this logic for all readings, I suggest you abstract it through a reading function:
sprintf(query,"select username, password from accounts where username='%s' and password='%s'\n", username, passwd);
Calling it like this:
#include <string.h>
#include <stdio.h>
void ler_string(char *destino, size_t tamanho){
fgets(destino, tamanho, stdin);
size_t ultima_pos = strlen(destino) - 1;
if (destino[ultima_pos] == '\n'){
destino[ultima_pos] = 'fgets(username, 25, stdin);
size_t ultima_pos = strlen(username) - 1;
if (username[ultima_pos] == '\n'){
username[ultima_pos] = 'void ler_string(char *destino, size_t tamanho){
fgets(destino, tamanho, stdin);
size_t ultima_pos = strlen(destino) - 1;
if (destino[ultima_pos] == '\n'){
destino[ultima_pos] = 'ler_string(username, 25);
';
}
}
'; //terminar a string no local onde está o '\n'
}
';
}
}
int main(){
char username[25];
char passwd[45];
printf("Input your name ->");
ler_string(username, 25);
printf("Input your password->");
ler_string(passwd, 45);
char query[128];
sprintf(query,"select username, password from accounts where username='%s' and password='%s'\n", username, passwd);
printf("%s", query);
return 0;
}
For what you are trying to build it becomes much simpler to interpolate the values you want within string
using sprintf
, which avoids having to do multiple concatenations:
sprintf(query,"select username, password from accounts where username='%s' and password='%s'\n", username, passwd);
Putting it all together your program would look like this:
#include <string.h>
#include <stdio.h>
void ler_string(char *destino, size_t tamanho){
fgets(destino, tamanho, stdin);
size_t ultima_pos = strlen(destino) - 1;
if (destino[ultima_pos] == '\n'){
destino[ultima_pos] = '%pre%';
}
}
int main(){
char username[25];
char passwd[45];
printf("Input your name ->");
ler_string(username, 25);
printf("Input your password->");
ler_string(passwd, 45);
char query[128];
sprintf(query,"select username, password from accounts where username='%s' and password='%s'\n", username, passwd);
printf("%s", query);
return 0;
}
See your run on Ideone
Note :
I recommend that you pay attention to MySQL injection attacks, which is something that is susceptible to this approach without controlling the input that the user gives in the program.