lundi 10 février 2020

Why %n in scanf returning 0 when reading a string from console

I tried to write a program which takes a line from user (console) until a comma, full stop or newline character is encountered and tell how many characters read following the specific pattern.

The string is read correctly but the count is not accurate.

#include <stdio.h>

int main()
{
    int n;
    char s[100];


    // The following line should read a string until (. or , or new-line in encountered) 
    // and %n should tell me the no of characters it read until that point
    scanf("%[^.,\n]s%n", s, &n);


    // The String in okay
    printf("%s\n", s);

    // But count of characters read is 0
    printf("%d\n",n);

    return 0;
}

Aucun commentaire:

Enregistrer un commentaire