string - Why does the output of this C++ program produce a giant mess in cmd? -
i have since figured out how make program correct, wondering why incorrect program question follows produces whole bunch of characters , different machine information, , if such error damage machine:
exercise 3.10: write program reads string of characters including punctuation , writes read punctuation removed.
#include <iostream> #include <string> using std::string; using std::cin; using std::cout; using std::endl; int main() { string s("some! string!s."); (decltype(s.size()) index = 0; index != s.size(); ++index){ if (!ispunct(s[index])){ cout << s[index]; ++index; } else { ++index; } } return 0; }
now, know incorrect, , have since made version correctly output needed:
#include <iostream> #include <string> using std::string; using std::cin; using std::cout; using std::endl; int main() { string s("some! string!s."); (decltype(s.size()) index = 0; index != s.size(); ++index){ if (!ispunct(s[index])){ cout << s[index]; } } return 0; }
why did first 1 produce mess of code? also, when there if , no else, thought when reaches "empty" or non-existing else stops; why, in second program, move on next character , restarts loop after hitting empty else?
- your string 15 characters long.
- the incorrect code increments character index 2 on each iteration rather 1.
- you're terminating loop when index exactly equal length of string (15) rather testing out-of-bounds condition.
- when character index 14 (corresponding '
.
' character) index increment 16, length of string 15,16 != 15
loop continues , undefined memory past end of string read , written output stream.