Reputation: 143
i want to replace the newline
by \n
in a string and i am unable to do this
#include<stdio.h>
#define MAX 1000
void escape(char x[],char y[]);
main()
{
int c=0,i;
char s[MAX],t[MAX];
for(i=0; (c=getchar())!=EOF && i<MAX;i++)
s[i]=c;
s[i]='\0';
for(int k=0;k<i;k++)
printf("%c",s[k]);
escape(s,t);
}
void escape(char x[],char y[])
{
int j=0,m=0;
while(x[j]!='\0')
{
if (x[j]=='\n')
{
y[m++] = '\\';
y[m] = 'n';
}
y[m]=x[j];
j++;
m++;
}
y[m]='\0';
for(int k=0;y[k]!='\0';k++)
printf("%c",y[k]);
}
the o/p i get is:
my name is amol
^Z
my name is amol
my name is amol\
Upvotes: 1
Views: 64
Reputation: 1279
Here It self you can simply add that
for(i=0; (c=getchar())!=EOF && i<MAX;i++){
if(c=='\n'){
s[i++]='\\';
s[i]='n';
}
else
s[i]=c;
}
After Adding you \ and n
on your code you need to conitnue
the loop from
starting (or), remaining blocks you need to add on the else
part
Upvotes: 4
Reputation: 34585
You missed out an else
in the escape()
function, hence the 'n'
is being overwritten
if (x[j]=='\n')
{
y[m++] = '\\';
y[m] = 'n';
}
else // <<<--- added a line
y[m]=x[j];
Upvotes: 1