随机出现的字符
Random characters popping up
当我调试程序时,当输出带星号的行时,它会输出随机的字符流。
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 << "'sn" ;
strikes++;
}
else
{
cout << "There are " << numberOfLetters << " " << userInput << "'sn";
}
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缓冲区,但什么也没做。我也有所有必要的include文件(字符串和iostream(,所以这不是问题所在,而且我在主方法上方有命名空间std。
这不是一个有效的字符常量。
puzzle[inputPuzzle.size()+1] = '';
如果你想要一个终止字符,它应该是
puzzle[inputPuzzle.size()+1] = ' ';
或者只是
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() ] = ' ';
puzzle[inputPuzzle.size()+1] = '';
应该是
puzzle[inputPuzzle.size()+1] = ' ';
您试图将null终止符添加到字符串的末尾以表示结束,但"不完全是。
相关文章:
- 为什么 Serial.println(<char[]>);返回随机字符?
- 字符串-C++后显示的随机字符
- 将字符随机转换为大写的函数
- 生成随机.txt文件,10行,10列。充满随机:"*"、"#"、"@"。然后将随机字符替换为'P'
- 在 c++ 的 10x10 数组中生成特定数量的多个随机字符
- 使用指针编译代码后,.cpp文件将变为随机字符
- 生成随机字符/数字
- 随机字符,从强制转换 Arduino 字符串到 Excel BSTR 通过 c++ DLL
- 字符数组中的十六进制导致写入套接字时出现随机字符
- 如何在网格中放置随机字符
- 解压缩 TIFF 数据会打印随机字符
- 将一个随机的字符序列和int序列解析为单独的向量
- 尝试以随机字符(长读取)打印字符串返回结果
- 取消随机排列整数/字符数组
- UNIX API 调用:使用 read() 函数打开文件并将其打印到屏幕上会增加额外的随机字符
- 如何修复C++中的随机字符输出?
- 为什么从函数返回c弦乐会导致随机字符
- 生成唯一的随机字符并将其保存在数组中
- 编译器将随机字符添加到我的 char 数组中
- 随机化字符数组以显示随机密码