如何在 C++ 中添加 getline?

问题描述

我希望从我的作业的名称部分删除空格,这允许用户在我的产品列表中输入任何带有或不带有空格的名称。例如“电视架”,我认为 getline 函数会帮助我解决它,但我无法将 getline 函数添加到我的 main.js 中。有人可以帮我吗?

#include <bits/stdc++.h>
#include <iostream>
#include <string>
using namespace std;
struct product {
    char product_name;
    int no_of_purchase;
    int no_of_sales;
    double purchase_cost;
    double selling_price;
    double profit_loss;
    double percent_profit_loss;
    string product_sales;
};
bool Compare(product P1,product P2)
{
    return P1.percent_profit_loss > P2.percent_profit_loss;
}
int main()
{
    int n;
    cout << "Enter the number of the product:";
    cin >> n;
    cout << "\n";
    product Products[n];
    for (int i = 0; i < n; ++i) {
        cout << "Enter the name of the product: ";
        cin >> Products[i].product_name;
        cout << "Enter the number of " << Products[i].product_name << " purchased: ";
        cin >> Products[i].no_of_purchase;
        cout << "Enter the number of " << Products[i].product_name << " sold: ";
        cin >> Products[i].no_of_sales;

解决方法

老实说我不明白你的问题,但这可能对你有帮助

我将 product_name 数据类型从 char 更改为 string,因为 char 数据类型没有任何意义

#include <iostream>
#include <string>
using namespace std;
struct product {
    string product_name;
    int no_of_purchase;
    int no_of_sales;
    double purchase_cost;
    double selling_price;
    double profit_loss;
    double percent_profit_loss;
    string product_sales;
};
bool Compare(product P1,product P2)
{
    return P1.percent_profit_loss > P2.percent_profit_loss;
}
int main()
{
    int n;
    cout << "Enter the number of the product:";
    cin >> n;
    cin.ignore();
    cout << "\n";
    product Products[n];
    for (int i = 0; i < n; ++i) {
        cout << "Enter the name of the product: ";
        getline(cin,Products[i].product_name);
        cout << "Enter the number of " << Products[i].product_name << " purchased: ";
        cin >> Products[i].no_of_purchase;
        cout << "Enter the number of " << Products[i].product_name << " sold: ";
        getline(cin,Products[i].no_of_sales);
        cin.ignore();
    }
    return 0;
}