0
int main(int argc, char const *argv[])
{
    int t, n, i, count;
    char curr;
    long long int total;
    scanf("%d", &t);
    while(t--){
        count = 0;
        total = 0;
        scanf("%d", &n);
        for(i=0;i<n;i++){
            scanf("%c", &curr);
            if(curr == '1'){
                ++count;
            }
        }
        if(count == 1){
            printf("1\n");
        }
        else{
            total = count + (count * (count-1))/2;
            printf("%lld  %d\n",total, count);
        }
    }
    return 0;
}

When i enter the input in the following format,

1
4
1111

I'm expecting output as: 10 4
But what i get is : 6 3.

The Program is logically & syntatically correct and i'm just unaware of what actually went wrong here. Help will be appreciated.

taurus05
  • 2,491
  • 15
  • 28
  • You do know that `scanf` returns a value that should be checked – Ed Heal Feb 23 '19 at 07:32
  • @EdHeal, it return the number of characters that have been read. – taurus05 Feb 23 '19 at 07:34
  • Please re-read the documentation - https://linux.die.net/man/3/scanf - and check the return value and take appropriate action if it is not what is expected – Ed Heal Feb 23 '19 at 07:36
  • @EdHeal, i'm not concerned about the return value here. I just want to know, why am i not getting the expected output. First line in input denotes number of test cases, then 2nd line denotes the length of string and third line denotes the string value. So, instead of reading the whole string at once using `%s`, i'm reading it character by character using `%c`. I'm counting total number of 1's and then finally determining the total number of substrings that begin and end with 1. – taurus05 Feb 23 '19 at 07:43
  • 1
    You should be concerned with the return value. It has a purpose. Also good code is concerned with the return value – Ed Heal Feb 23 '19 at 07:44
  • So, i just tweaked it and did something like this `printf("%d ",scanf("%c", &curr));`. It prints 1 whenever a character is read and stored inside the variable curr. – taurus05 Feb 23 '19 at 07:45
  • 1
    `scanf("%c", &curr);` - is this reading the new line character? – Ed Heal Feb 23 '19 at 07:51
  • Just use scanf(" %c", &variable_name) Put a space before %c – Sayed Mohsin Reza Jun 29 '20 at 19:02

1 Answers1

3

After using scanf(...) for n (here 4), the newline character remains in the inputstream. The first character that is read in the for loop is the newline character \n.

You can use something like getchar() after reading n to remove the \n, but do this only if you are sure of the input format.

Also, as mentioned by Jonathan Leffler, scanf(" %c", &curr) seems to be a better alternative.

pmcarpan
  • 660
  • 6
  • 13