Harshil Soni
Harshil Soni

Reputation: 1

Why does the error "string subscript out of range" is appearing while debugging the below code

Here is the code. I am getting an error "string subscript out of range" while debugging the below code. So please find where the error is and the solution.

#include <iostream>
using namespace std;

int main()
{
    string s;
    int i = 0;
    for (int i = 0; i < 50; i++)
        s[i] = 'A';
    cout << s;
    return 0;
}

Upvotes: 0

Views: 30

Answers (1)

Mike Fisher
Mike Fisher

Reputation: 389

The problem is s[i] = 'A'; is changing the character at position i, but the string is empty and there is no character at that position. What you want to do is append a new character to the string like this s += 'A'; or s.push_back('A');.

Upvotes: 3

Related Questions