У всех отелей выводится одна цена что не так? Написано на С++
#include
#include
using namespace std;
int main()
{
int i;
int cn;
string gs[3];
for(i=0; i<3;i++)
{
cout<<"Vvedite nazvanie";
cin>>gs[i];
cout<<"Vvedite cenu";
cin>>cn;
if(cn<25000)
{
cout<<gs[i]<<endl;
}
}
for(i=0;i<3;i++)
{
cout<<"gs("<<i<<")="<<gs[i]<<endl;
cout<< gs[i]<<cn<<endl;
}
system("pause");
return 0;
}
C/C++
Что не так выводится одна цена
#include <iostream>
#include <string>
#include <vector>
using namespace std;
class Hotel {
string name_;
int cost_;
friend istream& operator>>(istream& in, Hotel& h) {
cout << "Название: ";
getline(in, h.name_);
cout << "Цена: ";
cin >> h.cost_;
in.ignore(numeric_limits<streamsize>::max(), '\n');
return in;
}
friend ostream& operator<<(ostream& out, const Hotel& h) {
out << h.name_ << ", " << h.cost_;
return out;
}
};
int main() {
system("chcp 1251 > nul");
vector<Hotel> price(3);
for (auto& hotel : price) cin >> hotel;
system("cls");
for (const auto& hotel : price) cout << hotel << '\n';
system("pause > nul");
}
#include <string>
#include <vector>
using namespace std;
class Hotel {
string name_;
int cost_;
friend istream& operator>>(istream& in, Hotel& h) {
cout << "Название: ";
getline(in, h.name_);
cout << "Цена: ";
cin >> h.cost_;
in.ignore(numeric_limits<streamsize>::max(), '\n');
return in;
}
friend ostream& operator<<(ostream& out, const Hotel& h) {
out << h.name_ << ", " << h.cost_;
return out;
}
};
int main() {
system("chcp 1251 > nul");
vector<Hotel> price(3);
for (auto& hotel : price) cin >> hotel;
system("cls");
for (const auto& hotel : price) cout << hotel << '\n';
system("pause > nul");
}
Одна цена описана, одна цена вводится, одна цена выводится.
Как написали - так работает.
string gs[3]; // <== массив названий отелей я так понимаю.
int cn; //<== цена. не массив.
Хорошо-бы, чтобы это было сделано структурой или классом. Я видел - Вы знаете что такое record в Pascal. В C++ вместо него struct сойдёт =)
_https://metanit.com/cpp/tutorial/5.8.php
Как написали - так работает.
string gs[3]; // <== массив названий отелей я так понимаю.
int cn; //<== цена. не массив.
Хорошо-бы, чтобы это было сделано структурой или классом. Я видел - Вы знаете что такое record в Pascal. В C++ вместо него struct сойдёт =)
_https://metanit.com/cpp/tutorial/5.8.php
С подсветкой синтаксиса https://pastebin.com/jbVVXZCq
//main.cpp
#include <iostream>
#include <string>
#include <vector>
#include "Hotel.h"
template<typename T>
T getNumberFromCin(std::string,
T min = std::numeric_limits<T>().min(),
T max = std::numeric_limits<T>().max()
);
int main()
{
std::vector<Hotel> hotels;
int count = 3;
for (int i = 0; i < count; i++)
{
std::string name;
int cost;
std::cout << "Enter Hotel name >>> ";
std::getline(std::cin, name);
cost = getNumberFromCin("Enter Hotel cost >>> ", 0, 25000);
hotels.push_back(Hotel(name, cost));
}
for (auto hotel : hotels) {
std::cout << hotel << std::endl;
}
system("pause");
return 0;
}
template<typename T>
T getNumberFromCin(std::string str, T min, T max) {
T num;
std::cout << str;
std::cin >> num;
while (num < min || num > max || std::cin.fail())
{
std::cout << "Invalid input!" << std::endl << str;
if (std::cin.fail())
{
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}
std::cin >> num;
};
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
return num;
}
//Hotel.h
#pragma once
#include <iostream>
class Hotel {
public:
Hotel(std::string name, int cost);
friend std::ostream& operator<< (std::ostream&, Hotel&);
std::string getName();
int getCost();
void setCost(int);
private:
Hotel();
std::string _name;
int _cost;
};
//Hotel.cpp
#include "Hotel.h"
std::ostream& operator<< (std::ostream& stream, Hotel& obj) {
return stream << obj._name << " : " << obj._cost;
}
Hotel::Hotel(std::string name, int cost): _name(name){
if (cost >= 25000)
throw new std::invalid_argument("Cost must be lower than 25000");
_cost = cost;
}
std::string Hotel::getName() {
return _name;
}
int Hotel::getCost() {
return _cost;
}
void Hotel::setCost(int newCost) {
_cost = newCost;
}
//main.cpp
#include <iostream>
#include <string>
#include <vector>
#include "Hotel.h"
template<typename T>
T getNumberFromCin(std::string,
T min = std::numeric_limits<T>().min(),
T max = std::numeric_limits<T>().max()
);
int main()
{
std::vector<Hotel> hotels;
int count = 3;
for (int i = 0; i < count; i++)
{
std::string name;
int cost;
std::cout << "Enter Hotel name >>> ";
std::getline(std::cin, name);
cost = getNumberFromCin("Enter Hotel cost >>> ", 0, 25000);
hotels.push_back(Hotel(name, cost));
}
for (auto hotel : hotels) {
std::cout << hotel << std::endl;
}
system("pause");
return 0;
}
template<typename T>
T getNumberFromCin(std::string str, T min, T max) {
T num;
std::cout << str;
std::cin >> num;
while (num < min || num > max || std::cin.fail())
{
std::cout << "Invalid input!" << std::endl << str;
if (std::cin.fail())
{
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}
std::cin >> num;
};
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
return num;
}
//Hotel.h
#pragma once
#include <iostream>
class Hotel {
public:
Hotel(std::string name, int cost);
friend std::ostream& operator<< (std::ostream&, Hotel&);
std::string getName();
int getCost();
void setCost(int);
private:
Hotel();
std::string _name;
int _cost;
};
//Hotel.cpp
#include "Hotel.h"
std::ostream& operator<< (std::ostream& stream, Hotel& obj) {
return stream << obj._name << " : " << obj._cost;
}
Hotel::Hotel(std::string name, int cost): _name(name){
if (cost >= 25000)
throw new std::invalid_argument("Cost must be lower than 25000");
_cost = cost;
}
std::string Hotel::getName() {
return _name;
}
int Hotel::getCost() {
return _cost;
}
void Hotel::setCost(int newCost) {
_cost = newCost;
}
Второй массив заведи для цен, такойже как и для названий
Похожие вопросы
- [c++] Почему при возврате строки по ссылке(const), она не выводится в консоль? Подробности внизу.
- Что за числа выводятся при переполнении int в C++?
- Помогите с задачей в C++ пожалуйста. Какое условие правильно написать в Z чтобы выводилось сообщение "error!" ?
- Почему не выводится часть кода?
- Помогите найти ошибки в коде на C++, не выводится последняя строчка
- Измерение времени на си. Почему-то скорость сортировки массива выводится со второго раза.. И еще надо измерить память
- Структуры не выводятся, что делать?
- Помогите задача информатика 9 класс вычислить значение интеграла а выводится -nan(ind)
- SQL. Выводятся не все данные. 4 задача.
- Навеял вопрос "Выводилась как нянька детям "(+)
Для чтения/записи полей можешь создать методы, чисто с академическим интересом, на практике создается исходя из архитектуры разрабптываемого приложения. Чаще всего как рука зайдет)