为什么这个 for 循环总是显示"o"。C++

Why this for loop always show 'o's.C++

本文关键字:显示 C++ for 循环 为什么      更新时间:2023-10-16

在这里,我编写了一个包含结构(向量(的代码。我使用了 for 循环显示结构内的数据。我认为 for 循环有问题。你们能纠正我吗?

#include <iomanip>
#include <iostream>
#include <string>
#include <vector>
using namespace std;
struct coffee {
string name;
int itemprice;
string country;
int quantity;
};
float remainder, price2, price;
int main() {
int coffeetype = 1;
vector<coffee> coffee_drink(7);
"Espresso", 120, "Italy", 20;
"Iced coffee", 150, "France", 20;
"Long black", 80, "Austral", 20;
"Americano", 100, "America", 20;
"Latte", 200, "Italy", 20;
"Irishcoffee", 130, "Ireland", 20;
"Cappuccino", 180, "Italy", 20;
cout << fixed;
cout << setprecision(2);
for (int i = 0; i != coffee_drink.size(); ++i)
cout << "n " << i + 1 << ") " << coffee_drink[i].name << "tt"
<< coffee_drink[i].itemprice << "tt" << coffee_drink[i].country
<< "tt(" << coffee_drink[i].quantity << ") remaining";
}

您可以使用大括号初始值设定项来简化操作:

int main() {
int coffeetype = 1;
vector <coffee> coffee_drink =
{{ "Espresso", 120, "Italy", 20 },
{"Iced coffee", 150, "France", 20},
{"Long black", 80, "Austral", 20},
{"Americano", 100, "America", 20},
{"Latte", 200, "Italy", 20},
{"Irishcoffee", 130, "Ireland", 20},
{"Cappuccino", 180, "Italy", 20}};
cout << fixed;
cout << setprecision(2);
int i = 0;
for (const auto & drink: coffee_drink)
cout << "n " << ++i << ") " << 
drink.name << "tt" << 
drink.itemprice << "tt" << 
drink.country << "tt(" << 
drink.quantity << ") remaining";
}

据我所知,您的 for 循环缺少一个封闭括号。但这不是主要问题。您需要解决的两件事是:

  1. 您不会向向量添加任何值。这可以通过使用push_back或在初始化时使用大括号初始值设定项列表来完成。
vector <coffee> coffee_drink;
coffee_drink.push_back({"Espresso", 120, "Italy", 20});
coffee_drink.push_back({"Iced coffee", 150, "France", 20 });

阿拉伯数字。

for (int i = 0; i != coffee_drink.size(); ++i){
cout << "n " << i+1 << ") " << coffee_drink[i].name << "tt" << coffee_drink[i].itemprice << "tt" << coffee_drink[i].country << "tt(" << coffee_drink[i].quantity << ") remaining";
}