Boris Bleha
Boris Bleha

Reputation: 11

c++ - string subscript out of range - where am I making a mistake?

Where am I making a mistake??

#include "stdafx.h"
#include <iostream>
#include <string.h>
#include <sstream>

using namespace std;

string input = "";
string slogovi = "";

int broj = 0;

void main()
{
    printf("Please enter a valid name:\n>");
    getline(cin, input);
    int c = input.length();
    for (int i = 0; i < c; i++) {
        if (input[i] == 'a' || input[i] == 'e' || input[i] == 'i' || input[i] == 'o' || input[i] == 'u') {
            slogovi[broj] = input[i];
            slogovi[broj + 1] = '-';
            broj += 2;
        }
        else {
            slogovi[broj] = input[i];
            broj++;
        }
    }

    printf("%s", slogovi);
    system("pause");
}

The thread 0x14d0 has exited with code -1073741510 (0xc000013a). The program '[5452] Strings.exe' has exited with code -1073741510 (0xc000013a).

Upvotes: 1

Views: 99

Answers (2)

MOJNICK
MOJNICK

Reputation: 81

http://en.cppreference.com/w/cpp/string/basic_string/operator_at: "Returns a reference to the character at specified location pos. No bounds checking is performed. If pos > size(), the behavior is undefined."

You could use resize() method, as size of your string is 0.

Upvotes: 2

NL628
NL628

Reputation: 438

The length of slogovi stays at 0 the whole time. I understand that you are trying to change it with slogovi[broj]=input[i], but you can't even use the [] operator because the length is 0.

Upvotes: 2

Related Questions