Alif Khair Alif Khair - 1 year ago 135
C Question

C Program Array more than 1 word

This question is from HackerRank, I try to use %[^\n]s for a long word. But, the output keep on producing .0

How to replace %[^\n]s to something else for the string to receive the input ?

Here is the input :

is the best place to learn and practice coding!

Here is my output :

HackerRank .0

This is the expected output :

HackerRank is the best place to learn and practice coding!

This is my full code, as you can see, it does not recognize %[^\n]s. How to solve this problem? Thank you.

Full code :

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

int main() {
int i = 4;
double d = 4.0;
char s[] = "HackerRank ";

// Declare second niteger, double, and String variables.
int value1, sum1, value2;
double e = 2.0, sum2;
char t[30];

// Read and save an integer, double, and String to your variables.
scanf(" %d", &value1);
scanf("%d", &value2);
scanf("%[^\n]s", t); //** POINT OF INTEREST **

// Print the sum of both integer variables on a new line.
sum1 = value1 + i;
printf("%d\n", sum1);

// Print the sum of the double variables on a new line.
sum2 = d * e;
printf("%.1lf\n", sum2);

// Concatenate and print the String variables on a new line
// The 's' variable above should be printed first.
printf("%s %s", s, t);

return 0;

Answer Source

Considering your input-output examples, I amended your code like this:

char t[256]; // the string "is the best place to learn and practice coding!" MUST FIT!!!
scanf("%d", &value1);
scanf("%lf", &d); // NOT %d, %lf !!! &d or &e - I don't know - depends on you
scanf("\n%[^\n]", &t);
printf("%s%s", s, t); // you don't need a space, since your "s" already contains it.

Works fine for me.

UPD: Now it actually works fine.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download