James Balajan James Balajan - 3 months ago 29
C Question

Strange behaviour printf - c lang

I was recently trying to make a program to escape escape sequences in a string. Everything looks fine and there are no error messages yet when I test the program, nothing prints.

#include <stdio.h>

#define MAXLINE 1000

void escape(char s[], char t[]);

int main () {
char s[MAXLINE], t[MAXLINE];
int i, c;
for (i = 0; (c = getchar()) != EOF; i++)
c = s[i];
s[i] = '\0';
escape(s, t);
printf("%s\n",t);
return 0;
}

void escape(char s[], char t[]) {
int j = 0, i;
for (i = 0; s[i] != '\0'; i++) {
switch (s[i]) {
case '\n':
t[j] = '\\';
t[++j] = 'n';
++j;
break;
case '\t':
t[j] = '\\';
t[++j] = 't';
++j;
break;
default:
t[j] = s[i];
++j;
break;
}
}
t[j] = '\0';
}


Thank you.

Answer

The for loop in the main function should be:

for (i = 0; (c = getchar()) != EOF; i++)
    s[i] = c;