程序在输入10个字符串后崩溃

时间:2014-02-16 12:33:15

标签: c++ string list

该程序应该从键盘上读取10个字符串以及形成字符串列表的其他5个单词。它将随机选择列表中的一个单词并替换所有vovwels。然后程序会要求你猜测。但是,在输入10个字符串之后程序崩溃了....

#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <ctime>
#include <string>

int randomnum(){
int g, r, f = 0;
/*init random number generator*/
srand(static_cast<unsigned int>(time(0)));/*get a random num*/
g = rand();
r = (g % 13) + 1;
return(r);
}

int main(){
int k,l,f;
std::string *str = new std::string[14];
str[0] = "computer";
str[1] = "television";
str[2] = "keyboard";
str[3] = "magazine";
str[4] = "book";

std::cout<< "please enter 10 strings" <<std::endl;/*get strings into the array*/
    for(int i = 5;i < 15; i++){
            std::cin>>str[i];
    }
k = randomnum();
std::string e = str[k];
l= e.size();

char letter[l - 1];
strcpy(letter,e.c_str());

for(int i = 0; i < l; i++){
        if(letter[i] == 'a' || letter[i] =='e' || letter[i] == 'i' || letter[i] == 'o' || letter[i] == 'u' || letter[i] == 'A'|| letter[i] == 'E' || letter[i] =='I'
            || letter[i] == 'O'||letter[i] == 'U'){/*replace the vowel*/
            letter[i] = '_';
        }

    }
std::cout<< "Please guess the word: " << letter <<std::endl;
std::string gue;
std::cin>> gue;
if(gue == e) {
f++;
std::cin.clear();
std::cout<<"You guessed correct after "<< f << "guesses, Do you want to play it again?"<< std::endl;/*check the number and return the result*/
}
if(gue == "zzz"){
    exit(0);
}
else{
    f++;
    std::cin.clear();
    std::cout<<" Incorrect, guess another one!"<< std::endl;
    std::cin>>gue;
}
std::cin.clear();
std::cin.sync();
return 0;

}

2 个答案:

答案 0 :(得分:2)

std::string *str = new std::string[14];

应该是

std::string *str = new std::string[15];

否则你只能在阵列中再添加9个字符串

答案 1 :(得分:1)

这是因为你为14个字符串分配了空间,但写了 15 字符串。我的建议是不要使用指针,而是使用std::vector