int id = 22; string name = "添加书籍"; int number = 20; int price = 10; string author = "添加成功"; printf("请输入I D:"); scanf("%d", &id); printf("请输入书名:"); scanf("%s", &name); printf("请输入数量:"); scanf("%d", &number); printf("请输入价格:"); scanf("%d", &price); printf("请输入作者:"); scanf("%s", &author); printf("测试当前信息---id=%d,name=%s,number=%d,price=%d,author=%s",id,name,number,price,author); string sql = "insert into books values(" + to_string(id) + ",'" + name + "'," + to_string(number) + "," + to_string(price) + ",'" + author + "')"; int ret = mysql_query(&mysql, sql.c_str()); if (ret) { cout << "Error: Query[添加成功] fail." << endl; break; }优化这段c++代码,换一种更好的输出方式
时间: 2024-01-18 14:04:35 浏览: 70
可以使用cout代替printf输出,同时使用<<符号连接字符串和变量,使代码更简洁易懂。优化后的代码如下:
```
int id = 22;
string name = "添加书籍";
int number = 20;
int price = 10;
string author = "添加成功";
cout << "请输入ID:";
cin >> id;
cout << "请输入书名:";
cin >> name;
cout << "请输入数量:";
cin >> number;
cout << "请输入价格:";
cin >> price;
cout << "请输入作者:";
cin >> author;
cout << "测试当前信息---id=" << id << ",name=" << name << ",number=" << number << ",price=" << price << ",author=" << author << endl;
string sql = "insert into books values(" + to_string(id) + ",'" + name + "'," + to_string(number) + "," + to_string(price) + ",'" + author + "')";
int ret = mysql_query(&mysql, sql.c_str());
if (ret) {
cout << "Error: Query[添加成功] fail." << endl;
break;
}
```
阅读全文