【发布时间】:2017-03-03 15:20:40
【问题描述】:
为什么 push_back 没有按预期工作?很困惑为什么它不适用于我下面的当前代码
using namespace std;
void addItem(vector<string>& STRING, string item)
{
STRING.push_back(item);
}
int main()
{
string item;
vector<string> STRING(100);
ifstream myFile;
myFile.open("food.txt");
if (myFile.is_open()) //code where I store my data into the array
{
int i = 0;
while (!myFile.eof())
{
getline(myFile, STRING[i]);
i++;
}
}
myFile.close();
cin >> item;
addItem(STRING, item);
int x = 0;
while(!STRING[x].empty()) //code to print the current array
{
cout << STRING[x];
printf("\n");
x++;
return 0;
}
}
我初始化数组的方式有问题吗?因为当我使用 CodeBlocks 时,有 0 个错误和 0 个警告,所以在我运行它之前我认为它很好。
【问题讨论】:
-
请提供minimal reproducible example,我们可以重现该问题..
-
如果您的
printList是您在最小代码中显示的while循环,那么这是完全错误的。此外,您从未真正检查过向量的长度是否发生了变化,那么您是如何确定它没有变化的呢? -
重构您的代码,使数字 100 不会在任何地方硬编码。将
STRING初始化为空并使用push_back从头开始添加。将变量重命名为strings,因为STRING看起来像一个宏。不要在循环条件中使用eof。最后,避免using namespace std;。哦,考虑std::cout而不是printf。
标签: c++ string vector push-back