0

I am new to coding. This is a Question from the #30 days code on Hackerrank. But, I'm unable to solve it. can anyone help me by telling me what's the problem here?

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

int main() {
    int i = 4;
    double d = 4.0;
    char s[] = "Hello ";
    // Declare second integer, double, and String variables.
    int j;
    char *ptr=s;
    double c;
    char p[100];
    // Read and save an integer, double, and String to your variables.
    scanf("%d",&j);
    scanf("%lf",&c);
    scanf("%[^\n]%*c",p);
    // Print the sum of both integer variables on a new line.
    printf("%d\n",i+j);
    printf("%.1lf\n",c+d);
    printf("%s%s",s,p);
    // Print the sum of the double variables on a new line.
    
    // Concatenate and print the String variables on a new line
    // The 's' variable above should be printed first
    return 0;
}

It is showing the result

Input:
12
4
Output:
16
8.0
Hello o}┌vl
╤

As you can see I want to print concatenated string but it wouldn't even allow me to input the data into the string.

  • Aniket Mani, Curious, why code `scanf()` with a `"%*c"` after `"%[^\n]"`, but not a `"%*c"` after `"%lf"`? – chux - Reinstate Monica Mar 01 '22 at 17:13
  • @chux-ReinstateMonica Isn't `"%*c"` for characters, but `"%lf"` is a floating-point type data type. If I'm wrong, then I'm curious. – Aniket Mani Mar 01 '22 at 17:24
  • Dodged answering with a question - hmmm. `"%*c"` is for reading 1 character and not saving it. Why code that after `"%[^\n]"`? – chux - Reinstate Monica Mar 01 '22 at 17:32
  • @chux-ReinstateMonica I only added `"%*c"`, because the program was going to be checked by hackerrank, I didn't know how they would give inputs. – Aniket Mani Mar 01 '22 at 18:00
  • @chux-ReinstateMonica You see I'm new , I don't even understand concepts like `buffer`, – Aniket Mani Mar 01 '22 at 18:02
  • _buffer_ has nothing to do with the problem. Code here lacks simple checks of the return values of `scanf()` which would have quickly informed that `scanf("%[^\n]%*c",p);` failed. Tip: always check the return value of input functions. `scanf("%[^\n]%*c",p);` --> `if (scanf("%[^\n]%*c",p) != 1) puts("Fail");` – chux - Reinstate Monica Mar 01 '22 at 18:08

1 Answers1

0

I guess you press the Enter key for all input?

That Enter key will be added as a newline in the input buffer.

The %[^\n] format stops reading once it find a newline. And the first character it reads is a newline. So it doesn't read anything, and the array p will remain uninitialized with indeterminate contents.

You need to tell scanf to skip the leading newline, which is done by adding an explicit space in the format string:

scanf(" %99[^\n]",p);
//     ^
// Note space here

Note that I limit the input to 99 characters, which will not overflow the buffer. And also note that you don't need to read the newline after the string.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621