2016-02-01 59 views
1

我使用C++創建了該程序,該程序要求用戶使用大小寫字母輸入電影標題。它確定並顯示標題中的大寫和小寫字母的數量。然後它創建3個字符串,將原件中的所有字符都轉換爲大寫,然後轉換爲小寫,然後轉換爲相反的情況。它分開顯示這些字符串。顯示大寫和小寫字母的數量後出現問題。該程序輸出一條錯誤消息,指出它必須請求運行時以不尋常的方式終止它。我需要一些幫助來確定問題並修復它。由於 這裏是我的代碼:由C++字符串程序導致的運行時錯誤

#include <cstdlib> 
#include <iostream> 
#include <string> 
#include <cctype> 

using namespace std; 

int main(int argc, char *argv[]) 
{ 
    string title, upper, lower, swap; 
    int upCount = 0, lowCount = 0; 

    cout << "Please enter your favorite movie title:\n(it should have upper and lowercase letters)" << endl; 
    getline(cin, title); 
    for (int i = 0; i < title.size(); i++) 
    { 
     if (isupper(title.at(i))) 
      upCount++; 
     else if (isalpha(title.at(i))) 
      lowCount++; 
    } 
    cout << title << " has " << upCount << " uppercase letters and " << lowCount << " lowercase letters." << endl; 
    for (int i = 0; i < title.size(); i++) 
    {  
     upper.at(i) = title.at(i); 
     lower.at(i) = title.at(i); 
     swap.at(i) = title.at(i); 
    } 
    for (int i = 0; i < title.size(); i++) 
    { 
     if (isupper(title.at(i))) 
      swap.at(i) = tolower(int(swap.at(i))); 
     else 
      swap.at(i) = toupper(int(swap.at(i))); 
     upper.at(i) = toupper(int(upper.at(i))); 
     lower.at(i) = tolower(int(lower.at(i))); 
    } 
    cout << upper << endl 
     << lower << endl 
     << swap << endl; 

    system("PAUSE"); 
    return EXIT_SUCCESS; 
} 
+0

你做了什麼調試代碼?它失敗了什麼? – jmarkmurphy

+0

@jmarkmurphy它似乎在第二個循環之後的任何地方都失敗了。我不知道任何方式來調試,就像我通常會因爲它在運行時崩潰。 – CZou48

+0

你有權訪問源代碼調試器嗎?如果不是的話,你可以輸出簡單的消息到日誌文件或控制檯,比如「我到了這裏」,甚至可能爲該位置提供一些重要的變量值。這可能需要幾次迭代,但是您可以縮小故障位置。 – jmarkmurphy

回答

2

你永遠不會初始化upperlower,或swap爲任意值。當你做upper.at(i)lower.at(i)swap.at(i)程序將中斷。

您可以通過第二循環前設置upperlowerswap都等於title解決這個問題。

變化:

... 
    cout << title << " has " << upCount << " uppercase letters and " << lowCount << " lowercase letters." << endl; 
    upper = lower = swap = title; //Add this 
    for (int i = 0; i < title.size(); i++) 
... 

輸出:

Please enter your favorite movie title: 
(it should have upper and lowercase letters) 
V for Vendetta 
V for Vendetta has 2 uppercase letters and 10 lowercase letters. 
V FOR VENDETTA 
v for vendetta 
v FOR vENDETTA 
+0

對不起,如果我現在真的很愚蠢,但我不完全瞭解你指出的錯誤。我認爲它不會超出範圍,因爲標題的長度總是比最後一個索引多一個,<運算符可以防止它比最後一個索引更遠。在第二個for循環中,我將'upper','lower'和'swap'設置爲'title'。然後我將它們設置爲大寫,小寫或相反版本。 – CZou48

+0

@ CZou48你說得越界越好。我讀了錯誤的陳述。但是,從第二個循環開始,'upper','lower'和'swap'都是未初始化的,這意味着你不能使用'.at()'來設置任何東西。 –

+0

你能告訴我如何解決這個問題嗎?如何在不知道用戶將爲「title」輸入的情況下初始化這些字符串。 – CZou48

相關問題