Home > Software design >  Why newline does not print?
Why newline does not print?

Time:10-24

#include <stdio.h>
#include <string.h>

char str[50];

int main() {

    int hasSign = 0;

    printf("Enter your email: ");
    scanf("%s", str);

    // email validation
    if (strchr(str, '@') != NULL) {
        hasSign = 1;
    }
    printf("%s", hasSign   "\n");
    
    return 0;
}

How can I print a newline when I am printing the value of hasSign like in the upper code?

CodePudding user response:

There is a big bitfall here in the line printf("%s", hasSign "\n" );

"\n" is actually a pointer to const char (const char *) which is array of two characters: [0] = '\n', [1] = '\0' so when you add hasSign to it, it is actually doing pointer arithmetic.

To make it clear by example, let's say hasSign equals 0 so hasSign "\n" evaluates to 0 "\n" which is like &"\n"[0] = pointer to '\n' so a new line will printed in this case.

But when hasSign equals 1 so hasSign "\n" evaluates to 1 "\n" which is like &"\n"[1] = pointer to '\0' which is a null character or in other words 'nothing' and therefore nothing will be printed in this case.

To your question:

How can I print a newline when I am printing the value of hasSign like in the upper code?

you can do it like printf("%d\n", hasSign);

CodePudding user response:

You cannot concatenate strings with in C, nor convert numbers to strings by adding a number and a string. Your program compiles because hasSign "\n" is not a syntax error: adding a string and an integer evaluates to a pointer inside the string. The program will output a newline if hasSign is 0 and nothing of hasSign equals 1.

Here is a modified version that illustrates printf usage for string and integer arguments:

#include <stdio.h>
#include <string.h>

int main() {
    char str[50];
    int hasSign = 0;

    printf("Enter your email: ");
    if (scanf("Is", str) != 1) { // prevent scanf from writing beyond s[49]
        // exit upon input error
        return 1;
    }

    // email validation
    if (strchr(str, '@') != NULL) {
        hasSign = 1;
    }
    printf("email: %s, hasSign: %d\n", str, hasSign);
    
    return 0;
}
  • Related