簡體   English   中英

斷言錯誤,字符串下標超出范圍

[英]Assertion error, string subscript out of range

我幾乎完成了這個菜單並按照我想要的方式工作。 但是,當我按Enter而不輸入任何內容時,我收到一個斷言錯誤。 這是代碼

#include <iostream>
#include <cstdlib>
#include <string>
#include <sstream>
#include <iomanip>


using namespace std;

bool menu ()
{
 string input = "";
 bool exitVar;

 do
 {
 system("cls");

 cout << "               _       _   _   _       _   _ _ _  " << endl
      << "              |_|_   _|_| |_| |_|_    |_| |_|_|_| " << endl
      << "              |_|_|_|_|_| |_| |_|_|_  |_| |_|_    " << endl
      << "              |_| |_| |_| |_| |_| |_|_|_| |_|_|   " << endl
      << "              |_|     |_| |_| |_|   |_|_| |_|_ _  " << endl
      << "              |_|     |_| |_| |_|     |_| |_|_|_| " << endl
      << "               _ _   _       _   _ _ _   _ _ _   _ _     _ _ _   _ _      " << endl
      << "             _|_|_| |_|     |_| |_|_|_| |_|_|_| |_|_|_  |_|_|_| |_|_|_    " << endl
      << "            |_|_    |_|  _  |_| |_|_    |_|_    |_|_|_| |_|_    |_|_|_|   " << endl
      << "              |_|_  |_|_|_|_|_| |_|_|   |_|_|   |_|_|   |_|_|   |_|_|_    " << endl
      << "             _ _|_| |_|_| |_|_| |_|_ _  |_|_ _  |_|     |_|_ _  |_| |_|_  " << endl
      << "            |_|_|   |_|     |_| |_|_|_| |_|_|_| |_|     |_|_|_| |_|   |_| " << endl;

 cout << "\n            Welcome to Psuedo Mine Sweeper!!\n\n\n\n";

 cout << "                  <S>TART"
     << "\n\n                   <E>XIT\n\n";



    cout << "\t\t\tPlease enter a valid menu option: ";
    getline(cin,input);

    input[0] = toupper(input[0]);

}while(input[0] != 'S' && input[0] != 'E' || input.length() != 1 || cin.peek() != '\n');

if (input[0] == 'S')
    exitVar = true;
else
    exitVar = false;

return exitVar;

}

我對調試斷言值沒有太多經驗。 我試着單獨運行菜單

這里的問題是當你輸入getline設置input為空字符串,因為沒有輸入輸入。

這意味着它的長度為0,但是當你調用input[0]時,你要求input[0]第一個字符。 由於它沒有,它會拋出一個斷言錯誤。

要解決這個問題,在調用getline檢查input是否為空之后,如果是,請使用continue再次啟動循環。

您需要更改循環條件。

while (input.length() != 1 || (toupper(input[0]) != 'S' && toupper(input[0]) != 'E'));

|| 從左到右進行測試,因此檢查第一個字符之前必須檢查長度是否正確。 它也有助於將toupper作為循環條件的一部分,因為這樣首先檢查長度。 我也刪除了對cin.peek()的調用,不確定我理解那是什么。

你可以用一些布爾邏輯重寫整個事情,使其更清晰。

while (!(input.length() == 1 && (toupper(input[0]) == 'S' || toupper(input[0]) == 'E')));

通常,更少的否定是更容易理解的復雜布爾邏輯。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM