2013-04-15 58 views
0

當我調試我的程序時,它在輸出帶星號的行時輸出隨機字符流。彈出的隨機字符

int main() 
{ 
string inputPuzzle; 
cout << "Enter a word or set of words: "; 
getline(cin, inputPuzzle); 
char* puzzle = new char[inputPuzzle.size()+1]; 
memcpy(puzzle, inputPuzzle.c_str(), inputPuzzle.size()+1); 
puzzle[inputPuzzle.size()+1] = ''; 
int strikes = 0; 
char userInput; 
char* userSoln = new char[inputPuzzle.size()]; 
for (int i = 0; i < inputPuzzle.size(); i++) 
{ 
    userSoln[i] = '-'; 
    if (puzzle[i] == ' ') 
    { 
     userSoln[i] = ' '; 
    } 
} 
bool solved = false; 
int numberOfLetters; 
for (;;) 
{ 
    numberOfLetters = 0; 
    cin >> userInput; 
    for (int i = 0; i < inputPuzzle.size(); i++) 
    { 
     if (userInput == puzzle[i]) 
     { 
      numberOfLetters++; 
      userSoln[i] = puzzle[i]; 
     } 
    } 
    if (numberOfLetters == 0) 
    { 
     cout << "There are no " << userInput << "'s\n" ; 
     strikes++; 
    } 
    else 
    { 
     cout << "There are " << numberOfLetters << " " << userInput << "'s\n"; 
    } 
    if (userSoln == puzzle) 
    { 
     break; 
    } 
    if (strikes == 10) 
    { 
     break; 
    } 
    **cout << "PUZZLE: " << userSoln << "\n";** 
    cout << "NUMBER OF STRIKES: " << strikes << "\n"; 
} 
if (strikes == 10) 
{ 
    cout << "Sorry, but you lost. The puzzle was: " << puzzle; 
} 
else 
{ 
    cout << "Congratulations, you've solved the puzzle!!! YOU WIN!!!!!"; 
    } 
} 

我試過清理cin緩衝區,但沒有做。我也有所有必要的包含文件(字符串和iostream),所以這不是問題,我在主方法之上的命名空間std。

回答

0

這不是一個有效的字符常量。

puzzle[inputPuzzle.size()+1] = ''; 

如果你打算終止字符,它應該是

puzzle[inputPuzzle.size()+1] = '\0'; 

或只是

puzzle[inputPuzzle.size()+1] = 0; 

,或者你可以更換這兩行

memcpy(puzzle, inputPuzzle.c_str(), inputPuzzle.size()+1); 
puzzle[inputPuzzle.size()+1] = ''; 

strcpy

strcpy(puzzle, inputPuzzle.c_str()); 

編輯:

你還需要在打印前把終止字符在userSoln末。

userSoln[ inputPuzzle.size() ] = '\0'; 
+0

我仍然得到一個隨機字符串末尾的星號行。 – SwervinPervan

+0

@ user2283639看我的編輯。 :) –

+0

它現在有效。謝謝! – SwervinPervan

0
puzzle[inputPuzzle.size()+1] = ''; 

應該

puzzle[inputPuzzle.size()+1] = '\0'; 

你試圖空終止添加到字符串的結束意味着結束,而是「」是不是這麼回事。