Home > OS >  How do i solve this question related to string_Concatenation using C?
How do i solve this question related to string_Concatenation using C?

Time:03-02

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.

CodePudding user response:

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("            
  • Related