【问题标题】:How to add getline in c++?如何在 C++ 中添加 getline?
【发布时间】:2021-05-26 22:54:05
【问题描述】:

我希望从我的作业的名称部分中删除空格,这允许用户在我的产品列表中放置任何带有或不带空格的名称。例如“TV stand”,我认为 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;

【问题讨论】:

标签: c++ function integer main getline


【解决方案1】:

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

我将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;
}

【讨论】:

    猜你喜欢
    • 2013-05-27
    • 2015-05-24
    • 1970-01-01
    • 2021-02-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-17
    相关资源
    最近更新 更多