2014-02-16 71 views
-1

該程序應該從鍵盤讀取10個字符串以及5個字符串形成一個列表。它會隨機選取列表中的一個單詞並替換所有vovwels。然後程序會要求你猜。然而,在程序崩潰後,我進入10串....輸入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; 

} 

回答

1

這是因爲你的14串分配空間,但寫字符串。我的建議是不使用指針,但是std::vector

+0

我們還沒有在課堂上教這個...謝謝! – JuneWitt

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

應該

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

否則你將只能以9個字符串添加到陣列