简体   繁体   中英

Converting from letter into a word

Overall this is a small portion of the assignment but this function is giving me an error "Debug Assertion Failed!"

void English_to_SMS(void)
{
    int i;
    bool vowel;
    string word;
    string letter;

    cout << "Enter y, n or m: ";
    cin >> word;
    for (int i = 0; i <= word.length(); ++i)
    {
        letter = word[i];
        if (letter == "y") {
        cout << "yes";
        }
        else if (letter == "n") {
            cout << "no";
        }
        else if (letter == "m") {
            cout << "maybe";
        }
        else
        {
            cout << letter ;
    }
}

I took a screenshot of the error message: http://i.imgur.com/maQN7Vs.png

The error says:

Debug Assertion Failed!

Program: ..ects]English.SMS_Translator\\Debug\\English._SMS_Translator.exe File:e:\\microsoft visual studio 10.0\\vc\\include\\xstring Line:1440

Expression: string subscript out of range

For information on how your program can cause an assertion failure, see the Visual C++ documentation on asserts.

(Press retry to debug the application)

Any help or suggestion to solve this error would be greatly appreciated.

for (int i = 0; i <= word.length(); ++i)

Should be

for (int i = 0; i < word.length(); ++i)

Subscript ranges of N-sized container go from 0 to N-1

There are several mistakes in your function. The main mistake is that it is unclear what the function does.:) Either it asks the user to enter only a single character or a word of characters.

The valid range of indices for class std::string is [0, length() -1]. So instead of

for (int i = 0; i <= word.length(); ++i)

there must be

for (int i = 0; i < word.length(); ++i)

But it would be even better if you would write

for ( string::size_type i = 0; i < word.length(); ++i )

The secons mistake is the declaration of variable i

void English_to_SMS(void)
{
    int i;

that is not used in the function because in the for loop you declare another local variable i that hides the previous declaration. So you may remove statement

    int i;

Also I do not see any sense to declare an object of type std::string that to keep only one character. So instead of declaration

string letter;

I would use declaration

char letter;

For example

char letter;
//...

    letter = word[i];
    if (letter == 'y') {

Declaration

bool vowel;

is also not used in the function.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM