-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.c
More file actions
77 lines (65 loc) · 1.92 KB
/
main.c
File metadata and controls
77 lines (65 loc) · 1.92 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
#include <stdio.h>
#include <stdlib.h>
#include "sqlite3.h"
#define DB_FILE "votes.db"
#define CANDIDATES_COUNT 3
struct Candidate {
int id;
char name[50];
};
struct Candidate candidates[CANDIDATES_COUNT] = {
{1, "Candidate 1"},
{2, "Candidate 2"},
{3, "Candidate 3"}
};
void print_candidates() {
for (int i = 0; i < CANDIDATES_COUNT; i++) {
printf("%d. %s\n", candidates[i].id, candidates[i].name);
}
}
int main() {
sqlite3 *db;
char *err_msg = 0;
int rc = sqlite3_open(DB_FILE, &db);
if (rc != SQLITE_OK) {
fprintf(stderr, "Cannot open database: %s\n", sqlite3_errmsg(db));
sqlite3_close(db);
return 1;
}
char *create_table_sql = "CREATE TABLE IF NOT EXISTS votes(candidate_id INT);";
rc = sqlite3_exec(db, create_table_sql, 0, 0, &err_msg);
if (rc != SQLITE_OK) {
fprintf(stderr, "SQL error: %s\n", err_msg);
sqlite3_free(err_msg);
sqlite3_close(db);
return 1;
}
printf("Please choose a candidate by entering a number:\n");
print_candidates();
int chosen_candidate_id;
scanf("%d", &chosen_candidate_id);
int chosen_candidate_index = -1;
for (int i = 0; i < CANDIDATES_COUNT; i++) {
if (candidates[i].id == chosen_candidate_id) {
chosen_candidate_index = i;
break;
}
}
if (chosen_candidate_index == -1) {
printf("Invalid candidate ID.\n");
sqlite3_close(db);
return 1;
}
char *insert_vote_sql;
asprintf(&insert_vote_sql, "INSERT INTO votes(candidate_id) VALUES(%d);", chosen_candidate_id);
rc = sqlite3_exec(db, insert_vote_sql, 0, 0, &err_msg);
if (rc != SQLITE_OK) {
fprintf(stderr, "SQL error: %s\n", err_msg);
sqlite3_free(err_msg);
sqlite3_close(db);
return 1;
}
printf("Your vote has been recorded. Thank you for voting!\n");
sqlite3_close(db);
return 0;
}