如何存储多个用户输入,然后以C++显示它们

How to store multiple user inputs and then display them all in C++

本文关键字:然后 C++ 显示 输入 用户 何存储 存储      更新时间:2023-10-16

我是 c++ 的新手,我需要使用我的函数来存储多个用户输入,然后打印多个用户输入。但是,我的代码只执行一个用户输入。我应该将其存储在数组中吗?它是不言自明的代码,因此您可以跳到底部并查找"??存储不变??">

#include <iostream>
using namespace std;
// Will display all bids
void displayBid(string &bidTitle, string &fundPerson, string &vehicleId, float &bidAmount)
{
cout << "Title: " << bidTitle << endl;
cout << "Fund: " << fundPerson << endl;
cout << "Vehicle: " << vehicleId << endl;
cout << "Bid Amount: " << bidAmount << endl;
}
// Ask the user for title, person, vehicleId, amount
void getBid(string &bidTitle, string &fundPerson, string &vehicleId, float &bidAmount)
{
cout << "Enter Title: ";
cin.ignore();
getline(cin, bidTitle);
cout << "Enter Fund";
cin.ignore();
getline(cin, fundPerson);
cout << "Enter Vehicle ID: ";
cin.ignore();
getline(cin, vehicleId);
cout << "Enter Bid Amount: ";
cin.ignore();
cin >> bidAmount;
}
// Loops through adding bids or displaying bids
main(void)
{
string title, person, id;
title = "";
person = "";
id = "";
float amount;
amount = 0.0;
int choice = 0;
while (choice != 9) {
cout << "Menu:" << endl;
cout << "  1. Enter Bid" << endl;
cout << "  2. Display Bid" << endl;
cout << "  9. Exit" << endl;
cout << "Enter choice: ";
cin >> choice;
switch (choice) {
case 1:
??storeinvariable?? = getBid(title, person, id, amount);
break;
case 2:
// display variable??
displayBid(title, person, id, amount);
break;
}
}
cout << "Good bye." << endl;
return 1;
}

你可以为此使用数组。但是,它必须包含两种不同的数据类型。您可以制作一个void*s 的数组或向量,但这不是最好的解决方案。

您可以创建自己的类型(可能是struct(来存储用户输入的数据,如下所示:

typedef struct {
std::string bidTitle;
std::string fundPerson;
std::string vehicleId;
float bidAmount;
} Bid;

一旦你定义了struct,你就可以让你的函数使用这种数据类型。

相关文章: