arrays - 如何在显示数组值后创建的数组中选择内存。程序运行时如何用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
}
解决方案
根据您更新的查询,要求退出条件,我修改了代码。请注意,我曾经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;
}
}
}
推荐阅读
- excel - 数一数。列表中的对
- python-3.x - 隐藏小部件时如何阻止 PyQt5 删除小部件?
- php - 名言正则表达式不起作用
- javascript - 在上传期间调整图像大小(Canvas 和 SimpleImage 库)
- pocketsphinx - ubuntu的声音文件到文本文件语音识别,特别是pocketsphinx的使用
- python - 操作系统模块脚本做的事情但是在终端上抛出错误
- django - 如何检查Django Views列表中的对象
- java - 打印 AVL 树的顶部“m”个元素
- google-bigquery - 使用 Google bigquery 将查询结果导出到云存储中的输出文件
- php - 尝试使用 php 访问 json 数组数据