【发布时间】:2019-11-15 14:52:53
【问题描述】:
我声明了一个vector<string>,但我什至无法编译它。我尝试了很多方法,但都没有奏效。
我正在尝试写出 x.surname.push_back(word)[i] 但它确实写错了,我不知道如何正确编写它并使其能够编译。
#include <cstring>
#include <iostream>
#include <vector>
using namespace std;
int main() {
int number, i = 0;
string word;
struct donators {
vector<string> surname;
vector<int> amount;
} x;
cout << "How many donators do you want to register? " << endl;
cin >> number;
for (i = 0; i < number; i++) {
cout << "Surname: ";
cin >> word;
x.surname.push_back(word)[i];
cout << "Amount: ";
x.amount.push_back(i);
cin >> x.amount[i];
}
cout << "OUR GORGEUS DONATORS: " << endl;
for (i = 0; i < number; i++) {
if (x.amount[i] >= 10000) {
cout << "Surname: " << x.surname(word)[i];
cout << "Amount: " << x.amount[i] << endl;
}
else if (x.amount[i] < 10000) {
cout << "Lack of surnames!" << endl;
}
}
cout << "OUR CASUAL DONATORS: " << endl;
for (i = 0; i < number; i++) {
if (x.amount[i] < 10000) {
cout << "Surname: " << x.surname(word)[i];
cout << "Amount: " << x.amount[i] << endl;
} else if (x.amount[i] >= 10000) {
cout << "Lack of surnames!" << endl;
}
}
return 0;
}
还有一件事。如何造句“没有姓氏!”写一次?在某些情况下,它会被写出两倍或更多倍的冗余内容。
【问题讨论】:
-
如果您遇到编译器错误,请将其添加到您的问题中。
-
你为什么要把
[i]放在所有的末尾?那是什么意思?请说明你想让x.surname.push_back(word)[i]做什么而不是现在做什么。 -
正确的包含是
<string> -
您的问题是您认为
std::vector<std::string>的工作方式与std::vector<int>不同。它们的工作方式相同,并且应该使用相同的方法。你使用amount(几乎)正确,以同样的方式使用surname。 -
请帮自己一个忙,获取a good C++ book。您不会通过尝试随机事物(例如
x.surname(word)[i])来学习 C++。此外,迭代工作会有所帮助:您的程序有几个语法和逻辑错误。不要试图一次编写整个程序。写出有用的东西并扩展它们,一旦发现错误就修复它们。从输入和输出单个名称开始,然后输入和输出名称列表等。