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

1

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).

c++
string
asked on Stack Overflow Nov 23, 2017 by Boris Bleha • edited Nov 24, 2017 by Grant Birchmeier

2 Answers

2

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.

answered on Stack Overflow Nov 23, 2017 by NL628
2

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.

answered on Stack Overflow Nov 23, 2017 by MOJNICK

User contributions licensed under CC BY-SA 3.0