我的程序应该要求用户添加一个单词,然后将其添加到string数组中,之后将打印出所有单词.但是,程序在while循环中崩溃,并且字符串不会添加到数组中.
#include <iostream>
int main()
{
int counter = 0;
bool isRunning = true;
std::string listofthings[]
{
};
while(isRunning)
{
char play;
std::string word;
std::cout << "Enter a word" << std::endl;
std::cin >> word;
listofthings[counter] = word;
counter++;
std::cout << "Word added! q to Quit, any other key to continue" << std::endl;
std::cin >> play;
if(play == 'q')
isRunning = false;
}
int listnr = sizeof(listofthings)/sizeof(listofthings[0]);
for(int i = 0; i < listnr; i++)
{
std::cout << listofthings[i] << std::endl;
}
}
Run Code Online (Sandbox Code Playgroud)
您定义listofthings为空C样式数组(零元素).
std::string listofthings[]
{
};
Run Code Online (Sandbox Code Playgroud)
正如AndyG所指出的那样,语言需要大于零的大小,因此你的程序是不正确的.
所以,当你使用它时,
listofthings[counter] = word;
Run Code Online (Sandbox Code Playgroud)
行为是未定义的,在您的情况下,程序崩溃.
建议:改造listofthings一个std::vector
std::vector<std::string> listofthings;
Run Code Online (Sandbox Code Playgroud)
并使用emplace_back()或添加元素push_back()
listofthings.emplace_back(std::move(word));
Run Code Online (Sandbox Code Playgroud)
不需要counter和listnr(你可以使用listofthings.size())和打印周期成为
for ( auto const & str : listofthings )
std::cout << str << std::endl;
Run Code Online (Sandbox Code Playgroud)