Sindre
Sindre

Reputation: 83

I have a little code in C which compiles, but gives wrong answer

I am very new to C programming. I want to give input for number and for a string. Then print it out. the program compiles but I get this output "You wrote 0". Any tips will be really valuable. Thank you

#include <stdio.h>

int main(int argc, char **argv)
{
int number;
char cc[30];
scanf("Write number: %d\n", &number);
scanf("Write phrase: %s\n", cc);
printf("You wrote : %d %s",number,cc);  
return 0;
}

Upvotes: 1

Views: 115

Answers (3)

nishantbhardwaj2002
nishantbhardwaj2002

Reputation: 767

First of all, you can't print using a scanf function. For this purpose you have to use a printf statement before a scanf statement.

printf("Write number: ");
scanf("%d", &number);
printf("\nWrite phrase: ");
scanf("%s", cc);
printf("\nYou wrote : %d %s",number,cc);

Secondly, you should not use '\n' after the format specifier in the scanf statement. The scanf statement uses '\n' i.e. newline, as the indicator that you have finished giving input to your function. Even the following code will work:

scanf("%d", &number);
scanf("%s", cc);

And a better way to get this done is:

scanf("%d %s", &number, cc);

Upvotes: 1

Simon Richter
Simon Richter

Reputation: 29618

The format string you give to scanf is the format of the input it expects.

You want to use

printf("Write number: ");  // no trailing \n here
scanf("%d", &number);

Upvotes: 3

Lee Duhem
Lee Duhem

Reputation: 15121

For scanf("Write number: %d\n", &number); to success, you need to input something like "Write number: 42" and enter, I do not think this is what you want to do. You could replace that with this

printf("Write number: ");
scanf("%d", &number);

Another scanf() has the same problem and fix.

Upvotes: 4

Related Questions