0

I've wrote some code about arrays and strings, which I'm not comfortable working with(I'm a newbie). This bug is a runtime issue, since the compiler didn't yell at me when this program compiled. I'm totally stuck about this, and don't know why this happened.

# include<iostream>
# include<cstdio>
# include<cstring>
# include<string>
using namespace std;
int main() {
    char in[100];
    gets(in);
    int len = strlen(in);
    std::string s(in);
    int count = 0;
    for (int i = 0; i < len; i++) {
        if (s.at(i) == ' ') {
            count += 1;
        }
    }

    int i = 0;
    char rec[100];
    for (int j = 0; j < len; j++) {
        if (s.at(j + 1) != ' ') {
            i += 1;
            rec[i] = s.at(j);
        } else {
            i += 1;
            rec[i] = s.at(j);
        }
    }

    for (int m = 0; m < i; m++) {
        cout << rec[m];
    }

    //cout << count;

}

Suppose the user input is "Hello World" (without the quotes). It was supposed to return "Hello", but instead got a error saying the following:

terminate called after throwing an instance of 'std::out_of_range'
  what():  basic_string::at

This application has requested the Runtime to terminate it in an unusual way.
Please contact the application's support team for more information.

and what followed was a popup to report to the Microsoft team.

andy zhang
  • 21
  • 6
  • 3
    When `j` is equal to `len - 1`, when what index will `j + 1` be in `s.at(j + 1)`? – Some programmer dude Apr 05 '19 at 11:49
  • 1
    Oh please do [not use `gets()`](https://stackoverflow.com/questions/1694036/why-is-the-gets-function-so-dangerous-that-it-should-not-be-used). – dedObed Apr 05 '19 at 11:50
  • 1
    what is the code actually supposed to do? instead of fixing the bug I'd rather fix the whole code to be less suspectible to bugs ;). Why do you need to fiddle around with indexes? Why `char[]` instead of `std::string`? – 463035818_is_not_an_ai Apr 05 '19 at 11:51
  • This is supposed to flip the sentence around. For example, Hello World is going to be World Hello. I haven't finished writing the code yet, and ran into some bugs for testing. – andy zhang Apr 05 '19 at 12:55

1 Answers1

0

Check "at" and have a close look at some programmers dude comment again:
http://www.cplusplus.com/reference/array/array/at/

 It throws out_of_range if n is out of bounds.

Oh and please, especially when asking others: Dont use 1-letter-variables
Dont use variable names such as "count" or "rec" that are hard to interpret

Ozzy
  • 64
  • 4