c++14 - C++: same code and compiler, but different output after each build -
greetings stackoverflow's community! need someone's help.
here code supposed print 2 integers, first , last indexes of shortest sentence's symbols in string given (str). can see, shortest sentence in string "hey!!!"; character 'h' has index 16 , last exclamation mark has index 21, correct output should be: 16 21.
i've compiled code using cppshell (cpp.sh) , here's deal: same code compiled same compiler gives different result @ each new attempt build it:
attempt #1: 16 21
attempt #2: 145921712 4196790
attempt #3: 16 21
attempt #4: 16 21
attempt #5: 1453219648 4196790
etc.
please explain me strange situation? i'm novice @ c++, therefore may not see obvious mistakes in code.
#include <iostream> #include <cstdlib> #include <clocale> #include <cstdio> #include <cstring> using namespace std; int main() { setlocale(lc_ctype, "rus"); char str[] = " what's up? hey!!! it's practice... how you?? "; char* ptr = str; char* p = ptr; int startsym, endsym; int startsymmin = 0, endsymmin = 2000; while(*ptr) { if (*ptr > 64 && *ptr < 91) // capitalized letters 'a'-'z' { startsym = strchr(ptr, *ptr)-p; while(*ptr) { if ((*ptr == '!' && *(ptr+1) != '!' && *(ptr+1) != '?') || (*ptr == '?' && *(ptr+1) != '!' && *(ptr+1) != '?') || (*ptr == '.' && *(ptr+1) != '.')) { endsym = strchr(ptr, *ptr)-p; break; } ptr++; } } if (endsym - startsym < endsymmin - startsymmin) { startsymmin = startsym; endsymmin = endsym; } ptr++; } cout << startsymmin << " " << endsymmin << endl; return 0; }
look @ first iteration of loop. first if
false, @ second if
, use variables (startsym
, endsym
) not initialized.
initialize these variables well, , program work ok. sample string, @ least (i think need solve other edge cases make program work ok every strings).
tips:
- use debugger find out why program misbehaves (but, unfortunately, in particular case, debugger may not tell what's problem).
- if use msvc, can turn on run-time checks uninitialized variables (/rtcu)
- if use linux, can use valgrind catch error (and lot of other kind of errors)
Comments
Post a Comment