/*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>
usingnamespace 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/
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.