gpt4 book ai didi

c++ - 字符串/整数 vector - cout

转载 作者:行者123 更新时间:2023-11-28 00:19:31 30 4
gpt4 key购买 nike

我尝试制作一个程序,要求用户输入 10 个人吃过的煎饼,然后列出它们。人名和吃过的煎饼分别存储在不同的 vector 中。从 vector 中打印值时出现错误。

#include <iostream>
#include <bits/stl_vector.h>
#include <bits/stl_bvector.h>

using namespace std;

int main() {
vector<int> pancakes;
vector<string> name;
int temp_num;
for (int x = 0; x < 10; x++) {
cout << "Enter pancakes eaten by person " << x+1 << endl;
cin >> temp_num;
pancakes.push_back(temp_num);
name.push_back("Person " + x);
}
for (int x = 0; x < 10; x++){
cout << name[x] << " ate " << pancakes[x] << " candies." << endl;
}
return 0;
}

我收到的错误是“下标值不是数组。”。

最佳答案

您不能添加 std::string和一个 int , 所以这是不允许的

name.push_back("Person " + x);

但是,您可以使用 std::to_string 然后然后连接。

name.push_back("Person " + std::to_string(x));

我也不确定你为什么有 <bits>包括,你应该只有

#include <iostream>
#include <string>
#include <vector>

关于c++ - 字符串/整数 vector - cout,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28242248/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com