Printing array and getting garbage at end.

The program works with the exception that garbage is being displayed on the screen after the p has been stripped. I'm going nuts. Thanks in advance.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
  //Read characters into a char Array until the character 'p' is encountered, 
//up to a limit of 10 characters (including the terminating null character). 
//Extract the delimiter 'p' from the input stream and discard it.


#include "stdafx.h"
#include <iostream>
#include <string>
#include <iomanip>

using namespace std;

int main()
{

	char characterArray[10];
    char delimiter;
    int ArrayPos = 0;

	//read a string into character array 10 characters
    cout << "Enter a string: ";
	

    while(ArrayPos <= 10){

        //if the character is a p, we need to get rid of it.
        if(cin.peek() == 'p')
		{
            //extract the delimiter from the stream

			
            ArrayPos = 11;  //exit loop

        }
			else
			{
              characterArray[ArrayPos] = cin.get();
              ArrayPos++;
		    }

    }

    cout << characterArray << endl;

	system("pause");

	return 0;
     

}

You use <= on line 24, so you try to write to the 11th element of your array (that is characterArray[10]). This element doesn't exist.

The reason you get garbage characters is because your array of characters does not have a terminating null character to tell when the end of the string is, so it just keeps going and reading random memory until it happens to hit a 0.
Topic archived. No new replies allowed.