So I am writing a program that takes 4 inputs from the user: a username, a password, a phone number and an address; The program then uses sqlite3
database to insert this data into an existing table.
Here is the code:
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<sqlite3.h>
void newregister()
{
char new_user[200];
char new_pass[200];
char new_phone[200];
char new_address[200];
printf("Enter your desired username: \n");
fgets(new_user, 200, stdin);
printf("Enter your desired password: \n");
fgets(new_pass, 200, stdin);
printf("Enter your phone number: \n");
fgets(new_phone, 200, stdin);
printf("Enter your address: \n");
fgets(new_address, 200, stdin);
printf("new user = %s \n", new_user);
printf("new pass = %s \n", new_pass);
printf("new phone = %s \n", new_phone);
printf("new address = %s \n", new_address);
sqlite3 *db;
sqlite3_stmt *stmt;
int rc = sqlite3_open("test.db", &db);
if(rc != SQLITE_OK)
{
fprintf(stderr, "Problem opening Database: %s\n", sqlite3_errmsg(db));
}
char *sql = "INSERT INTO Users VALUES(?, ?, ?, ?, NULL, 0);";
rc = sqlite3_prepare_v2(db, sql, -1, &stmt, 0);
if (rc != SQLITE_OK)
{
fprintf(stderr, "Problem executing INSERT: %s\n", sqlite3_errmsg(db));
}
else
{
sqlite3_bind_text(stmt, 1, new_user, -1, SQLITE_STATIC);
sqlite3_bind_text(stmt, 2, new_pass, -1, SQLITE_STATIC);
sqlite3_bind_text(stmt, 3, new_phone, -1, SQLITE_STATIC);
sqlite3_bind_text(stmt, 4, new_address, -1, SQLITE_STATIC);
}
int step = sqlite3_step(stmt);
sqlite3_finalize(stmt);
sqlite3_close(db);
}
int main()
{
newregister();
return 0;
}
The problem that I'm facing is that it doesnt insert the lines properly even though the printf
seems to work fine.
Here is how the table looks like:
User Password Phone Address Cart Total_Price
---------- ---------- ---------- -------------------- ---------- -----------
user1 pass1 1234567890 Str user nr 1 0
user2 pass2 1234586970 Str user nr 2 0
user3 pass3 2138321321 Str user nr 3 0
user4 pass4 8908702131 Str user nr 4 0
user5 pass5 9082313123 Str user nr 5 0
user6 pass6 9083213123 Str user nr 6 0
user7 pass7 0932382383 Str user nr 7 0
user8 pass8 3829832323 Str user nr 8 0
user11
pass11
1234567890 strada broscautilor
0
If I used scanf
then the entries would go normally up to the point where I have a space because scanf
stops when it reaches whitespace. However I tried using scanf
with different formatting that allows whitespace and I have the same problem as well as the fact that scanf with the same formatting 4 times stops taking input after the third time.
Would like to know what I'm doing wrong.
The fgets
function reads a line of text and writes it including the newline into the given character array.
You'll need to strip out the newline before continuing with processing.
fgets(new_user, 200, stdin);
char *nl = strrchr(new_user, '\n');
if (nl) *nl = 0;