-1

The goal is to write a program that gets an integer N, then gets N names, as big as they can be, and outputs, for each name, an abreviated version, except for the last name.

Example: for the input: "Sydney Alton Clay Angel", it outputs "S. A. C. Angel".

The code below will work only for the first iteration. At the second name, when I press enter, it shows:

"terminate called throwing an instance of 'std::out_of_range' what(): basic_string::replace: __pos (which is 13) > this-->size <> (which is 12)"

or something like that. What is wrong?!

#include <iostream>
#include <string>
int main() {
    std::string a;
    int k = 1;
    int N;
    std::cin >> N;
    for (int l = 0; l < N; l++) {
        getline(std::cin, a);
        a[0] = toupper(a[0]);
        for (int i = 0; i < a.size(); i++) {
            if (a[i] == ' ') {
                a[i + 1] = toupper(a[i + 1]);
            }
        }
        for (int i = 0, j = 0; i < a.size(); i++, j++) {
            if (a[i] == ' ') {
                a.replace(k, j, ". ");
                k += 3;
                j = i - k + 1;
            }
            
        }
        std::cout << a << '\n';
    }
}
user4581301
  • 29,019
  • 5
  • 26
  • 45
Jonas
  • 1

0 Answers0