I am having some issues with the scanf function.
I am trying to printf a scanf result, but it only returns 0.00000
Can someone help me? Here is my code done so far:
#include <stdio.h>
int main() {
float grade;
char choise;
do {
printf ("Type your grade: ");
scanf("%f", &grade);
printf("Want to continue? s/n: ");
scanf(" %c", &choise);
printf("%s \n", &choise);
printf("%f", &grade);
}while(choise != 'n');
}
printf("%f", &grade); is wrong
try
printf("%f", grade);
But there are many other issues. At the very least, you must check the values returned by scanf, and you should use int main(void) or int main(int argc, char **argv). eg:
#include <stdio.h>
#include <stdlib.h>
int
main(void)
{
float grade;
char choise;
do {
printf("Type your grade: ");
fflush(stdout);
if( scanf("%f", &grade) != 1 ){
fprintf(stderr, "Invalid input\n");
exit(1);
}
printf("Want to continue? s/n: ");
fflush(stdout);
if( scanf(" %c", &choise) != 1 ){
fprintf(stderr, "Invalid input\n");
exit(1);
}
printf("%c\n", choise);
printf("%f\n", grade);
} while( choise != 'n' );
return 0;
}
If you don't check the value returned by scanf, you don't know if any data was written into the variable. Since neither choise nor grade is initialized, attempting to read those values if scanf did not assign to them is undefined behavior. The behavior is also undefined if the input stream contains a value that cannot be represented as a float (eg, if it is a value greater than FLT_MAX), but that's really just an argument for avoiding scanf rather than a suggestion to try to make scanf usable. You can try to use scanf to make a user friendly interface, but it's really not worth the effort. Much better to simply abort on bad input. (If you want a user friendly interface, I would recommend you are using the wrong language.) See http://sekrit.de/webdocs/c/beginners-guide-away-from-scanf.html for more details on why you really ought to just avoid scanf completely.
These calls of printf
printf("%s \n", &choise);
printf("%f", &grade);
are incorrect.
In the first call you are trying to output a single character as a string. In the second call you are trying to output a pointer of the type float * as an object of the type float.
Instead you have to write
printf("%c\n", choise);
printf("%f\n", grade);
The lines
printf("%s \n", &choise);
printf("%f", &grade);
are wrong.
They should be
printf("%c \n", choise);
printf("%f", grade);
The %s format specifier should only be used for strings (null-terminated sequences of characters), not individual characters. The expression &choice does not point to a string, as the character sequence is not null-terminated.
Also, the %c and %f format specifiers require values, not addresses, when using them with printf. Only when using them with scanf should you pass an address.
Related
I'm pretty new to C, and I have a problem with inputing data to the program.
My code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void) {
int a;
char b[20];
printf("Input your ID: ");
scanf("%d", &a);
printf("Input your name: ");
gets(b);
printf("---------");
printf("Name: %s", b);
system("pause");
return 0;
}
It allows to input ID, but it just skips the rest of the input. If I change the order like this:
printf("Input your name: ");
gets(b);
printf("Input your ID: ");
scanf("%d", &a);
It will work. Although, I CANNOT change order and I need it just as-is. Can someone help me ? Maybe I need to use some other functions. Thanks!
Try:
scanf("%d\n", &a);
gets only reads the '\n' that scanf leaves in. Also, you should use fgets not gets: http://www.cplusplus.com/reference/clibrary/cstdio/fgets/ to avoid possible buffer overflows.
Edit:
if the above doesn't work, try:
...
scanf("%d", &a);
getc(stdin);
...
scanf doesn't consume the newline and is thus a natural enemy of fgets. Don't put them together without a good hack. Both of these options will work:
// Option 1 - eat the newline
scanf("%d", &a);
getchar(); // reads the newline character
// Option 2 - use fgets, then scan what was read
char tmp[50];
fgets(tmp, 50, stdin);
sscanf(tmp, "%d", &a);
// note that you might have read too many characters at this point and
// must interprete them, too
scanf will not consume \n so it will be taken by the gets which follows the scanf. flush the input stream after scanf like this.
#include <stdlib.h>
#include <string.h>
int main(void) {
int a;
char b[20];
printf("Input your ID: ");
scanf("%d", &a);
fflush(stdin);
printf("Input your name: ");
gets(b);
printf("---------");
printf("Name: %s", b);
system("pause");
return 0;
}
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void) {
int a;
char b[20];
printf("Input your ID: ");
scanf("%d", &a);
getchar();
printf("Input your name: ");
gets(b);
printf("---------");
printf("Name: %s", b);
return 0;
}
Note:
If you use the scanf first and the fgets second, it will give problem only. It will not read the second character for the gets function.
If you press enter, after give the input for scanf, that enter character will be consider as a input f or fgets.
you should do this way.
fgetc(stdin);
scanf("%c",&c);
if(c!='y')
{
break;
}
fgetc(stdin);
to read input from scanf after reading through gets.
scanf("%d", &a); can't read the return, because %d accepts only decimal integer. So you add a \n at the beginning of the next scanf to ignore the last \n inside the buffer.
Then, scanf("\n%s", b); now can reads the string without problem, but scanf stops to read when find a white space. So, change the %s to %[^\n]. It means: "read everthing but \n"
scanf("\n%[^\n]", b);
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void) {
int a;
char b[20];
printf("Input your ID: ");
scanf("%d", &a);
printf("Input your name: ");
scanf("\n%[^\n]", b);
//first \n says to ignore last 'return'
//%[^\n] read until find a 'return'
printf("---------\n");
printf("Name: %s\n\n", b);
system("pause");
return 0;
}
The scanf function removes whitespace automatically before trying to parse things other than characters. %c, %n, %[] are exceptions that do not remove leading whitespace.gets is reading the newline left by previous scanf. Catch the newline usinggetchar();
scanf("%d", &a);
getchar(); // catches the newline character omitted by scanf("%d")
gets(b);
https://wpollock.com/CPlus/PrintfRef.htm
Just use 2 gets() functions
When you want to use gets() after a scanf(), you make sure that you use 2 of the gets() functions and for the above case write your code like:
int main(void) {
int a;
char b[20];
printf("Input your ID: ");
scanf("%d", &a);
//the change is here*********************
printf("Input your name: ");
gets(b);
gets(b);
//the change is here*********************
printf("---------");
printf("Name: %s", b);
system("pause");
return 0;
}
I have written a program to take input of two numbers and either add or subtract the numbers depending the operation specified.
Here is my code :
#include <stdio.h>
#include <stdlib.h>
int main()
{
float i, j, k;
char a;
printf("This is a program to add or subs two number.\n");
printf("Enter the first number : ");
scanf("%f", &i);
printf("Enter the second number : ");
scanf("%f", &j);
printf("Give your choice(+ or -): ");
scanf("%c", &a);
switch(a){
case '+' :
k = i + j;
printf("Sum = %f\n", k);
break;
case '-' :
k = i - j;
printf("Difference = %f\n", k);
break;
default:
printf("Cannot do this operation\n");
}
return 0;
}
This program takes input for the two numbers but skips input for operation and runs the default case. Please help!
(I am using gcc compiler).
The %c conversion specifier won't automatically skip any leading whitespace, so if there's a stray newline in the input stream (from a previous entry, for example) the scanf call will consume it immediately.
One way around the problem is to put a blank space before the conversion specifier in the format string:
scanf(" %c", &a);
The blank in the format string tells scanf to skip leading whitespace, and the first non-whitespace character will be read with the %c conversion specifier.
-Aditya
I am writing a simple quiz in C (using CodeBlocks 13.12)
It compiles, but doesn't work in second question. Whatever I will input, it always give answer 'that's sad'.
I can't understand what is wrong.
I came to this, where if I comment line 13 ( scanf("%d", &age); ) it's starting works ok for second question.
What the problem is?
#include <iostream>
#include <stdio.h>
#include <windows.h>
#include <clocale>
int main()
{
int age;
char S1;
printf("How old is your dog? \n");
scanf("%d", &age);
if (age <= 7)
{
printf(" very young. the end \n");
return 0;
}
else
{
printf("old dog. \n \n");
}
//question2
printf("Do you like dogs? y/n \n");
scanf("%c%c", &S1);
if (S1 == 'y')
{
printf("hey, that's nice \n");
}
else
{
printf(" that's sad :( . \n");
return 0;
}
return 0;
}
You cause undefined behavior by
scanf("%c%c", &S1);
scanf reads two chars, one stored in S1, one stored in some location on the stack because scanf expects a second char* to be supplied.
If your intention is to ignore the newline following the actual character, write
scanf("%c%*c", &S1);
Change the second scanf() to
scanf(" %c", &S1);
This would escape the left out newline character \n in the input buffer.
Plus, you are reading one char in this. So you need only one %c
scanf("%c", &S1);
is the correct way to input one character ,
How could I print char for given ASCII code value?..
I saw this question, my problem is similar, just contrary
Below is my program, but it doesn't work.
int main (){
int code; // code that user enters
char ch; //"codes" related ASCII charcter
printf("Enter a ASCII code value: \n");
scanf("%d", &code);
ch=code;
printf(" %c is cherechter that have %d ASCII code\n", &ch ,&code);
system("PAUSE");
return 0;}
In your code, you have to change your printf statement
printf(" %c is cherechter that have %d ASCII code\n", &ch ,&code);
to
printf(" %c is cherechter that have %d ASCII code\n", ch ,code);
because, to print the values, you don't need to supply the address of the variables. The variable name is enough.
Change your code to:
int main (){
char code; //change from int to char
char ch;
printf("Enter a ASCII code value: \n");
scanf("%c", &code);//ASCII is a character not integer
ch=code;
printf(" %c is cherechter that have %x and %d ASCII code\n", ch ,code,code);//don't print the address access the value
system("PAUSE");
return 0;}
I'm just starting to learn C and I'm having problem with stopping my program based on what the user inputted.
#include <stdio.h>
#include <stdbool.h>
int main()
{
int a;
int b;
char c[5];
printf("Enter the two values you like to compare, type stop to end.\n");
while (c != "stop")
{
scanf_s(" %d %d %s", &a, &b, &c);
if (!(a^b))
{
printf("both are equal\n");
getchar();
}
else
{
printf("both are not equal\n");
getchar();
}
}
printf("Thanks for playing.");
getchar();
return 0;
}
The problem that I'm having is having to put in another variable, c, in my scanf_s. How would I do it so that the user does not have to put in another word after the 2 numbers? Also how can I check if the user only input "stop" so that it will stop the program? Btw the way I have it right now also does not stop the program when I do "10 10 stop". Thanks.
remove & for c in scanf_s(" %d %d %s", &a, &b, &c);
use strcmp to compare strings.
if you need to ignore case while comparing use strcasecmp (for UNIX based systems) and stricmp (for windows).
Use do-while instead of while if you need to run the loop at least once.
Full Working Code:
#include <stdio.h>
#include <string.h>
int main()
{
int a;
int b;
char c[5] = {'\0'};
do {
printf("Enter the two values you like to compare, type stop to end.\n");
scanf("%d%d%s", &a, &b, c);
if (!(a^b))
{
printf("both are equal\n");
getchar();
}
else
{
printf("both are not equal\n");
getchar();
}
}
while (strcmp(c,"stop"));
printf("Thanks for playing.");
getchar();
return 0;
}
while (c != "stop")
You cannot compare strings in C like that, use memcmp() or strncmp() library functions available in string.h. Read about them to know how they can be implemented as condition in while loop.
Also, to get string input, use
scanf_s(" %d %d %s", &a, &b, c); // Remove that litle '&' before 'c'.
NOTE: The function scanf_s returns the number of inputs scanned correctly, you should check that before proceeding with input values.
To get the user to stop without explicitly entering "stop", many ways are there:
1) Use do-while loop and keep asking user if he wants to play more.
2) Use negative numbers input (say -1) to quit.
Use line below to make sure your 'c' scan your string entered.
scanf(" %d %d %s", &a, &b, c);
Edit:
Consider replacing your while with line below to make sure you stop works. Include "string.h"
while (strcmp(c,"stop"))
Here is the fixed version... I have add the comments in the code for understanding...
#include <stdio.h>
#include <string.h>
int main()
{
int a;
int b;
char c[5] = {'\0'};
printf("Enter the two values you like to compare, type stop to end.\n");
while (strcmp(c,"stop"))
{
scanf("%d%d%s", &a, &b, c);
if (!(a^b))
{
printf("both are equal\n");
getchar();
}
else
{
printf("both are not equal\n");
getchar();
}
}
printf("Thanks for playing.");
getchar();
return 0;
}
First, lets correct your program:
&c (third argument to scanf_s) is incorrect. It should be c (because it is already a pointer). According to docs, scanf_s requires sizes to be specified for all %s format strings; therefore, the way you are doing things now, you should have written scanf_s(" %d %d %4s", &a, &b, c);
The program would be much easier to use if you changed your logic to "enter a blank line to exit". You can test this looking at the return value of scanf_s, which will be the number of format strings correctly read from the input.
If you need to ask for strings, then allow either, and look at whatever the user wrote to see whether it was number or string:
#include <stdio.h>
#include <string.h>
int main() {
int a;
int b;
char c[32];
printf("Enter the two values to compare, or type stop to end.\n");
while (fgets(c, 31, stdin) != NULL && strncmp("stop\n", c)) != 0) {
// user did not request to exit and wrote something; maybe 2 numbers
if (sscanf(c, "%d %d", &a, &b) != 2) {
// but he did not write two numbers. Complain and repeat.
printf("please write two numbers to compare, or type stop to end.\n");
continue;
}
if (a == b) {
printf("both are equal\n");
} else {
printf("both are not equal\n");
}
}
printf("Thanks for playing.\n");
return 0;
}
fgets reads whole lines, and you can then try to parse them using sscanf. This has the advantage over common scanf that you can try to parse the same line in different ways, depending on what you find in it. Generally, you do not want to fill your code with getchar(). If you are debugging, your debugger will stop for you. If you are not debugging, you will want to test or use your program with input redirection, and getchar() is simply not needed.
Its because you are using &c instead of just c in scanf_s. Replace that and it should work. Also, c is a string, so, you have to use strcmp instead of !=.
An easier way to write this code would be::
int main()
{
int a;
int b;
char c;
do
{
printf("Would you like to play?\nPress 'Y' for 'Yes' or 'N' for 'No'\n");
scanf( "%c", &c ) ;
/*scanf_s( "%c", &c, 1 ) ; */
if( c != 'Y' && c != 'y' )
break ;
printf("Enter the two values you like to compare\n" ) ;
scanf(" %d %d", &a, &b);
if (!(a^b))
{
printf("both are equal\n");
getchar();
}
else
{
printf("both are not equal\n");
getchar();
}
}while(1) ;
printf("Thanks for playing.");
getchar();
return 0;
}