Calculate Total Price and Directly Insert into Database

Hi,

I want to calculate total price but the variable is string. Reason why I use string is I need to put the total price directly into database which is string resinsert_query(). I'm using VS 2019 and Xampp in this project. Can anyone help me how to calculate it ?

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
#include<iostream>
#include<mysql.h>
#include<Windows.h>
#include<string>
#include<istream>
#include<sstream>

  void Reservation()
{
	int c = 0;
	string ic;
	string name;
	string menu_id;
	string quantity_no;
	string total_price;
	string reserve_date;
	string reserve_address;
	string reserve_status;
	string menu_availability;

	cout << "\n\tPlace Your Order.... "<< endl;
	c++;
	cout << "\n\tReservation No : " << c << endl;
	cin.ignore();
	cout << "\n\tEnter Name  : ";
	getline(cin, name);
	cout << "\n\tEnter Complete Address : ";
	getline(cin, reserve_address);
	cout << "\n\tEnter Menu Code : ";
	getline(cin, menu_id);
	cout << "\n\tEnter Quantity Menu : ";
	getline(cin, quantity_no);
	cout << "\n\tDate Reservation (yyyy-mm-dd) : ";
	getline(cin, reserve_date);
	cout << "\n\tEnter Status Reservation (Pending/Approve) : ";
	getline(cin, reserve_status);

        //calculate total_price and directly into database

	string resinsert_query = "INSERT INTO reservation(cust_name,menu_id,quantity_no,reserve_date,reserve_address,reserve_status) VALUES ('" + name + "','" + menu_id + "','" + quantity_no + "','" + reserve_date + "','" + reserve_address + "','" + reserve_status + "')";
	const char* qs = resinsert_query.c_str();
	qstate = mysql_query(conn, qs);

	if (!qstate)
	{
		cout << endl << "\tSuccessfully Make the Reservation." << endl;
	}
	else
	{
		cout << "\tFailed!" << mysql_errno(conn) << endl;
	}
}
Last edited on
Well you store it as an int or a float, do your calculation using regular mathematical operations and then convert the result to a string.

1
2
3
std::ostringstream os;
os << some_numeric_result;
std::string thing_for_the_db = os.str();



And use some line breaks.
1
2
3
4
5
6
7
8
9
string resinsert_query = 
    "INSERT INTO reservation(cust_name,menu_id,quantity_no,reserve_date,"
    "reserve_address,reserve_status) VALUES ('"
    + name + "','" 
    + menu_id + "','" 
    + quantity_no + "','" 
    + reserve_date + "','" 
    + reserve_address + "','" 
    + reserve_status + "')";

1. Adjacent "" strings are joined by the compiler.
2. Newlines are valid wherever spaces are allowed.

Topic archived. No new replies allowed.