After entering some letters to myString, I get an output containing exact letters as myString with some weird, scrambled up characters. For example I type in "letters" and the output I have is the following:
letters ÷ìu ╝■( Bñìu¿☻÷u³■( ʶì Ä◄ÿub◄ÿu←öïÜ ÉpB º■( ( ─ ( î¯u Å{N´■ b◄ÿu─[uÉpB ö ( ¯pB ÉpB P4å Ç
Also this weird characters appear different with different inputs, but they don't change after a rebuild with the same input.
Here is the code I have wrote:
#include <iostream> using namespace std; int main() { constexpr int BUFFER_SIZE = 128; char myString[BUFFER_SIZE + 1] = {}; // + 1 for null. Initialize all with null. cout << "Enter a string: "; fgets(myString, BUFFER_SIZE, stdin); int myString_size = sizeof(myString); for (int i = 0; i < myString_size; i++) { cout << myString[i]; } system("PAUSE"); return 0; } Now, I know that fgets() function will place an new-line character in the end of letters but why those characters still appear?
strlen()rather thansizeof()to determine the size of all characters entered.