I recently did this question
Specification:
Input Format The first line contains the number of test cases, T. Next, T lines follow each containing a long string S.
Output Format For each long string S, display the number of times
SUVOandSUVOJITappears in it.
I wrote the following code for this :
#include <bits/stdc++.h>
using namespace std;
int main() {
    int t;
    cin >> t;
    while (t--) {
        int suvo = 0;
        int suvojit = 0;
        string s;
        cin >> s;
        for (int i = 0; i <= s.size() - 7; i++) {
            if (s.substr(i, 7) == "SUVOJIT")
                suvojit++;
        }
        for (int i = 0; i <= s.size() - 4; i++) {
            if (s.substr(i, 4) == "SUVO")
                suvo++;
        }
        cout << "SUVO = " << suvo - suvojit << ", SUVOJIT = " << suvojit << "\n";
    }
    return 0;
}
The code about gave out of bounds exception for substr() function for this test case:
15
RSUVOYDSUVOJITNSUVOUSUVOJITESUVOSUVOSGSUVOKSUVOJIT
SUVOJITWSUVOSUVOJITTSUVOCKSUVOJITNSUVOSUVOJITSUVOJITSUVOSUVOSUVOJITTSUVOJ
SUVOSUVOSUVOJITASUVOJITGCEBISUVOJITKJSUVORSUVOQCGVHRQLFSUVOOHPFNJTNSUVOJITKSSUVO
SUVOJITSUVOJITJGKSUVOJITISUVOJITKJLUSUVOJITUBSUVOX
MMHBSUVOFSUVOFMSUVOJITUMSUVOJITPSVYBYPMCSUVOJIT
OASUVOSUVOJITSUVOSTDYYJSUVOJITSUVOJITSUVO
RLSUVOCPSUVOJITYSUVOSUVOOGSUVOOESUVOJITMSUVO
WVLFFSUVOJITSUVOVSUVORLESUVOJITPSUVOJITSUVO
RSUVOSUVOJITQWSUVOUMASUVOSUVOJITXNNRRUNUSUVOJIT
HYLSSUVOSUVOSUVOJITPOSUVOJIT
DGMUCSSSUVOJITMJSUVOHSUVOCWTGSUVOJIT
OBNSSUVOYSUVOSUVOJITSUVOJITRHFDSUVODSUVOJITEGSUVOSUVOSUVOJITSUVOSUVOJITSSUVOSUVOSUVOSSUVOJIT
AG
NSUVOJITSUVOSUVOJIT
CGJGDSUVOEASUVOJITSGSUVO
However, when instead of using the s.size() function, I converted the string into a char constant and took the length of it using strlen, then the code caused no error and everything went smoothly.
So, my question is... Why did this happen?
This is my working code with the change:
#include <bits/stdc++.h>
using namespace std;
int main() {
    int t;
    cin >> t;
    while (t--) {
        int suvo = 0;
        int suvojit = 0;
        string s;
        cin >> s;
        int le = strlen(&s[0]);
        for (int i = 0; i <= le - 7; i++) {
            if (s.substr(i, 7) == "SUVOJIT")
                suvojit++;
        }
        for (int i = 0; i <= le - 4; i++) {
            if (s.substr(i, 4) == "SUVO")
                suvo++;
        }
        cout << "SUVO = " << suvo - suvojit << ", SUVOJIT = " << suvojit << "\n";
    }
    return 0;
}
 
     
     
    
