【问题标题】:Print out the input into an array by calling the function but its not working通过调用函数将输入打印到数组中,但它不起作用
【发布时间】:2021-01-10 02:49:52
【问题描述】:

我知道这是一个简单的问题解决方案,但我仍然无法弄清楚。我正在尝试通过调用函数将输入打印到数组中,但它不起作用。帮我。下面是代码。 main.cpp 和 groovy.h。供您参考,我是编程新手

这是我得到的输出

//main.cpp

#include <iostream>
#include "groovy.h"
#include <string>
#include <iomanip>
using namespace std;

void displayInventory(const groovy[], int);

int main() {
  int s;

  const int size = 20;
  groovy car[size];
  /*= { 
    groovy("M01", "Mazda CX5", 132403.00),
    groovy("M02", "Mazda CX3", 126829.00),
    groovy("M03", "Mazda 6 Grand Touring", 208408.00),
    groovy("M04", "Mazda CX8", 173038.00),
  };

  cout<<"\nList of available car : \n"<<endl;
  displayInventory(car, size);
*/
  string code, model;
  double price;

  cout<<"\nPlease enter model details :- "<<endl;
  cout<<"Model code : ";
  cin>>code;
  cout<<"Model name : ";
  cin>>model;
  cout<<"Model price : ";
  cin>>price;
  
  car[size].storeInfo(code, model, price);
  displayInventory(car, size);

  return 0;
}

void displayInventory(const groovy object[], int size){
  for (int i = 0; i < size; i++){
    cout<<setw(5)<<left<<object[i].getCode()
        <<setw(28)<<left<<object[i].getModel()
        <<"RM "<<right<<object[i].getPrice()<<endl;
  }
}

//groovy.h

#include <iostream>
#include <iomanip>
#include <string>
using namespace std;

class groovy{
  private:
    string modelCode;
    string model;
    double price;
  
  public:
    groovy(){
      modelCode = "XXX";
      model = " ";
      price = 0.0;
    }
    groovy(string c,string m, double p){
      modelCode = c;
      model = m;
      price = p;
    }
    void storeInfo(string c,string m, double p) {
      modelCode = c;
      model = m;
      price = p;
    }
    string getCode() const {
      string code = modelCode;
      return code;
    }
    string getModel() const {
      string m = model;
      return m;
    }
    double getPrice() const {
      double p = price;
      return price;
    }
};

【问题讨论】:

  • 预期输出是什么?
  • 您可能想使用std::vector

标签: c++ arrays string


【解决方案1】:
  car[size].storeInfo(code, model, price);

很糟糕,因为数组 car 只有 size 元素:car[0]car[size-1]

索引必须不小于0且小于size

试试

  car[0].storeInfo(code, model, price);

改为。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-12-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-29
    • 1970-01-01
    • 2016-01-07
    相关资源
    最近更新 更多