How do I get rid of garbage in my output?

My output is correct, it gives me the answer I want but it also displays some weird characters (garbage) in addition to the displayed answer.

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
/*Input a line of text in a character array line of size 80. Input two characters ch1 and ch2. Display the
count of ch1 in line and replace all the occurances of ch1 with ch2 and display the modifed line.*/
#include<iostream>
#include<cstring>
using namespace std;
int main()
{
    char line[80];
    char ch1, ch2;
    char i=0;

    cout<<"Enter a line of text: ";
    cin.get(line,80);

    cout<<"Enter a character to replace: ";
    cin>>ch1;

    cout<<"Enter a character to replace "<<ch1<<" with: ";
    cin>>ch2;

    for (int ctr=0; ctr<80; ctr++)
    {
        if(line[ctr]==ch1)
        {
            line[ctr]=ch2;
            i=i+1;
        }

    }


    cout<<endl;
    cout<<"Count of "<<ch1<<":"<<i<<endl;
    cout<<"New line: ";

    for (int ctr=0; ctr<80; ctr++)
    {

            cout<<line[ctr];
    }

    return 0;

}

Try initializing your array to all null characters when you create it. When your program creates the array, it currently doesn't do anything to change the contents of the memory that it uses. It just takes whatever is there, which likely explains the garbage in your output.

memset takes a buffer (your array), a character, and a length to fill the buffer with whatever character you want. In this case, I picked the null character, represented by \0.
http://www.cplusplus.com/reference/cstring/memset/
1
2
3
4
5
6
7
8
//...
#include <cstring>  //for memset
//...

char line[80];
std::memset (line,'\0',80);

//... 
Last edited on
When you display a char, it shows the ascii representation of the value. Use an int for 'i' instead of char. Also you don't need to output line one char at a time:
 
cout << "New line: " << line << endl;


The "extra junk" is random stuff that is in line because you aren't necessarily storing all 80 characters and you are printing all of them anyway.
Last edited on
Thank you so much! @booradley60
Some of the garbage was removed, yet I still get a happy face in this part of the output:

//...
cout<<endl;
cout<<"Count of "<<ch1<<":"<<i<<endl;
cout<<"New line: ";
//...

it says "count of " then a happy face! (garbage) lol... what should I do here?
Last edited on
Thank you so much!
Topic archived. No new replies allowed.