c++ - difference between string size() function and strlen in this particular case -


i did question

specification:

input format first line contains number of test cases, t. next, t lines follow each containing long string s.

output format each long string s, display number of times suvo , suvojit appears in it.

i wrote following code :

#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 = 0; <= s.size() - 7; i++) {             if (s.substr(i, 7) == "suvojit")                 suvojit++;         }         (int = 0; <= s.size() - 4; i++) {             if (s.substr(i, 4) == "suvo")                 suvo++;         }          cout << "suvo = " << suvo - suvojit << ", suvojit = " << suvojit << "\n";     }     return 0; } 

the code gave out of bounds exception substr() function test case:

15 rsuvoydsuvojitnsuvousuvojitesuvosuvosgsuvoksuvojit suvojitwsuvosuvojittsuvocksuvojitnsuvosuvojitsuvojitsuvosuvosuvojittsuvoj suvosuvosuvojitasuvojitgcebisuvojitkjsuvorsuvoqcgvhrqlfsuvoohpfnjtnsuvojitkssuvo suvojitsuvojitjgksuvojitisuvojitkjlusuvojitubsuvox mmhbsuvofsuvofmsuvojitumsuvojitpsvybypmcsuvojit oasuvosuvojitsuvostdyyjsuvojitsuvojitsuvo rlsuvocpsuvojitysuvosuvoogsuvooesuvojitmsuvo wvlffsuvojitsuvovsuvorlesuvojitpsuvojitsuvo rsuvosuvojitqwsuvoumasuvosuvojitxnnrrunusuvojit hylssuvosuvosuvojitposuvojit dgmucsssuvojitmjsuvohsuvocwtgsuvojit obnssuvoysuvosuvojitsuvojitrhfdsuvodsuvojitegsuvosuvosuvojitsuvosuvojitssuvosuvosuvossuvojit ag nsuvojitsuvosuvojit cgjgdsuvoeasuvojitsgsuvo 

however, when instead of using s.size() function, converted string char constant , took length of using strlen, code caused no error , went smoothly.

so, question is... why did happen?

this working code 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]);         (int = 0; <= le - 7; i++) {             if (s.substr(i, 7) == "suvojit")                 suvojit++;         }         (int = 0; <= le - 4; i++) {             if (s.substr(i, 4) == "suvo")                 suvo++;         }          cout << "suvo = " << suvo - suvojit << ", suvojit = " << suvojit << "\n";     }     return 0; } 

in 1 case, use size_t, in other case use int.

if length example 6 characters, s.size () - 7 not -1, 1 huge number , goes wrong. if write int len = strlen (...), len - 7 indeed -1 , fine.

when see number subtracted size_t, that's immediate red flag. write "i + 7 ≤ s.size()", not "i ≤ s.size() - 7".


Comments

Popular posts from this blog

java - SSE Emitter : Manage timeouts and complete() -

jquery - uncaught exception: DataTables Editor - remote hosting of code not allowed -

java - How to resolve error - package com.squareup.okhttp3 doesn't exist? -