,因爲我現在真的絕望了,我可以使用一些幫助。在這裏,看看這段代碼,然後看看輸出。什麼導致這個錯誤?我該如何解決它?
感謝任何形式的幫助!
代碼:C++如果其他人不按預期工作? (很奇怪的BUG)
while (1)
{
while (1)
{
cout << "Choose your username: ";
cin >> username;
std::strcpy (username1, username.c_str());
if (isdigit(username1[0]) || isdigit(username1[1]) || isdigit(username1[2]))
{
cout << "The first 3 characters HAVE to contain only letters!\n\a";
}
else if (username1[3] < 0) // I don't actually know why, but this works as intended o.O
{
cout << "Your username HAS to contain atleast 3 letters!\n\a";
}
else if (username1[10] > 0) // Works - dunno why o.0
{
cout << "Your username CAN ONLY contain maximum 10 characters!\n\a";
}
else
break;
}
輸出:
Choose your username: ko
Your username HAS to contain atleast 3 letters!
Choose your username: k
Your username HAS to contain atleast 3 letters!
Choose your username: kokokokokoo // Now that's > 10
Your username CAN ONLY contain maximum 10 characters! // Now this is okay BUT...
Choose your username: ko
Your username CAN ONLY contain maximum 10 characters! // Wrong error!
Choose your username: kok // This should be accepted!
Your username CAN ONLY contain maximum 10 characters! // Well, it is not... there should not be an error at all!
注重我在輸出增加,所以你知道什麼是錯的意見。 謝謝你所有的答案!
瞭解如何使用開發環境的調試器。現在是最好的時機。 – nvoigt
您需要檢查輸入字符串* first *的長度。否則,當用戶輸入一個短字符串時,您正在訪問無效字符。 –
您需要重置字符串後返回到循環 String = aaaaaaaaaa <= 10個字母 下一個循環它仍然有10個字母,所以做一個memcpy來清除內容或填充0。 – Lefsler