一个"cin"的多个输入

Multiple Inputs for one "cin"

本文关键字:输入 cin 一个      更新时间:2023-10-16

我的作业要求输出类似于ths:

示例输出:输入产品类型和销售数量(输入 Z 停止):A 2

产品 A 的总销售额 = 5.97 美元

字母表示对象

的价格,下面的数字表示对象的数量。那么我如何让我的 cin 同时获得对象和数量呢?我目前有:

#include "stdafx.h"
#include <iostream>
#include <cmath>
using namespace std;
int main()
{ 
    double ProfitA, ProfitB, ProfitC;
    double TotalA = 0;
    char type;
    int quant; 
    ProfitA = (1.99) * quant;
    ProfitB = (2.99) * quant;
    ProfitC = (3.99) * quant;
    cout << "Enter product type and quantity sold (enter -1 to stop)nn";
    cin >> type >> quant;
    switch (type)
    {
    case 'A':cout << "Total sales of product A =" << ProfitA << "n";
        break;
    case 'B':cout << "Total sales of product B =" << ProfitB << "n";
        break;
    case 'C':cout << "Total sales of product C =" << ProfitC << "n";
        break;
    }
正如

@Pete贝克尔指出的那样,您正在尝试在用户输入数量之前计算利润。

将您的代码更改为以下内容:

char type;
int quant; 
cout << "Enter product type and quantity sold (enter -1 to stop)nn";
cin >> type >> quant;
ProfitA = (1.99) * quant;
ProfitB = (2.99) * quant;
ProfitC = (3.99) * quant;

运行程序时,在每个输入后键入 enter。然后在运行程序之前,编辑您的代码以在输入后进行利润计算