首页 > 解决方案 > 如何在显示数组值后创建的数组中选择内存。程序运行时如何用cin选择值

问题描述

string bookname [5] = {"STPM BOOKS","SPM BOOKS","PMR BOOKS","TEXT BOOK","PRACTICAL BOOK"};
 float  price [5] = {30.90,24.90,19.90,45.90,15.90};


        for(int i = 0; i < 5 ; i++)
        {
            cout << i+1 << "book name " << bookname[i] << " ---- RM " << price[i] << endl;}

我想从数组中选择值,例如 stpm 书籍及其价格,并在从 cin 中选择并在执行代码时进行选择后将其显示到 cout

}

标签: arrays

解决方案


根据您更新的查询,要求退出条件,我修改了代码。请注意,我曾经getline(cin, answer)处理过输入。我使用 getline() 是因为我在使用getline()over时不太可能搞砸cin >> answer

请注意 getline(cin, answer) 为您做了一些事情:

  • 如果接收到输入,则返回 true
  • 填写答案
  • 获取整行,直到用户提供新行

因此,该行将while (std::getline(std::cin, answer) && answer != "n")得到一整本书,即使有空格。&& 允许在进入 while 循环体之前检查“n”的答案。因为答案是 a std::string,所以比较是 to "n",不是'n'

如果这对您有用,请接受答案。祝你好运!

#include <iostream>
#include <string>
#include <iomanip> // setprecision

int main()
{

  std::string bookname[5] =
      {"STPM BOOKS", "SPM BOOKS", "PMR BOOKS", "TEXT BOOK", "PRACTICAL BOOK"};

  float price[5] = {30.90, 24.90, 19.90, 45.90, 15.90};

  std::string answer;
  float cost;

  std::cout << "Please provide the name of a book or type 'n' to exit"
            << std::endl;
  // get one line into answer, and also exit while if answer is "n"
  while (std::getline(std::cin, answer) && answer != "n") {  
    bool found = false;
    for (int i = 0; i < 5; i++) {
      if (bookname[i] == answer) {
        std::cout << "The book " << bookname[i] << " costs $" << std::fixed
                  << std::setprecision(2) << price[i] << std::endl;
        found = true;
        break; // /no need to continue inside the for loop
      }
    }

    // on last loop, give up
    if (!found) {
      std::cout << "The book " << answer << " is not in our inventory"
                << std::endl;
    }
  }

}

推荐阅读