Farhan Fuad Farhan Fuad - 3 months ago 25
C Question

How to get newline sign using scanf?

I am trying to create a simple notepad-like program to type in command prompt. But can't exactly get to the next line by pressing "Enter" using scanf() function.

#include<stdio.h>
void main ()
{
char c;
for(;;){
scanf("%c", &c);
if(c == "\n"){
printf("\n");
}
else{
printf("%c", c);
}
}
}


(I know scanf() leaves the new char in buffer. I have tried my best to get rid of the problem. Used getch() function after than scanf() but I can't make it work. I have to understand this issue with the scanf() function so I would like to avoid alternatives like using string or something else)

Answer

Well, you're a little bit unfortunate. This is a popular issue at the beggining of C programming. In C there is a huge difference between '\n' and "n". The first one is single character, so the type of '\n' is char. The other one is a string, and strings in C are char[]s. It means that actually "\n" = ['\n', '\0'] as strings are terminated with '\0' in C.

Another thing is, that scanf ignores leading white signs and a new line is a white sign. If you want to get more characters use fgets instead. For reading single characted, scanf is still ok.

This was widely described in this stack overflow topic.

#include<stdio.h>
void main () {
    char c;
    for(;;){
        scanf("%c", &c);
       if(c == '\n'){
           printf("\n");
       } else{
             printf("%c", c);
       }
    }
}