Why is sscanf acting this way? - c

I thought that I understood C but i am having a hard time just writing a simple addition code for practice. When I run this code, int a is 0 every time. However, int b works fine. The idea here is that the input to the program is 8 + 9. Why does sscanf not recognize variable a?
#include <stdio.h>
#include <stdlib.h>
int plus(int a, int b){
return (a + b);
}
int main()
{
int a, b;
char input[100], op;
printf("...I am ZOLO...\n");
printf("...The most vercatile calculator known to man...\n");
printf("...Please enter your query:");
fgets(input, sizeof(input), stdin);
sscanf(input, "%d %s %d", &a, &op, &b);
printf("%d + %d = %d...", a, b, plus(a, b));
return 0;
}

Jonathon Reinhart has the correct answer. In this case, it's not just the undefined behavior problem, it's the fact that the compiler managed to allocate op just before a (in internal memory order) and your machine uses little-endian byte order so that the '\0' character stored after op wipes out the value that was previously stored to a.

Related

Input multiple integer values and print them in C

I'm new to C language. Here's the code I used to get input for a and b and print them. But I did not get the values I entered via the terminal can you explain why I got different values for a and b?
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
int main()
{
int a,b;
scanf("%d, %d", &a, &b);
printf("%d, %d", a, b);
return 0;
}
I entered 5 9 as inputs, but I got 5 and 16 as outputs.
You need to check the value of scanf() otherwise some or all the values you attempt to use are undefined. In your case the input you provided did not match the scanf() format string. I changed the format string to match the input you provided, removed headers that are not used and added a newline to your printf() statement:
#include <stdio.h>
int main(void) {
int a, b;
if(scanf("%d%d", &a, &b) != 2) {
printf("scanf failed\n");
return 1;
}
printf("%d, %d\n", a, b);
}
You don't have to use comma (,) to separate 2 inputs in scanf() function. This function automatically separates your inputs by number of occurrences of format specifiers i.e. %d in your case. However you have to separate variable addresses using comma.
Just use it like scanf("%d %d", &a, &b).

How to read abc.com like strings with scanf?

Im trying to read from stdin something like abc.com but a[0]='\0' after run scanf instead of 'a'. Im using %[^.] to read all character until find a '.'.
#include <stdio.h>
int main() {
char a[6];
char b[4];
int i = scanf("%[^.]%s", a, b);
printf("%d\n", i);
printf("a: %s\n", a);
printf("b: %s\n", b);
printf("%c\n", a[0]);
printf("%c\n", a[1]);
printf("%c\n", a[2]);
if (a[3]=='\0') puts("why?");
return 0;
}
Trying char b[5]; will get you an output of
2
a: abc
b: .com
a
b
c
It indicates that you have read 5 characters into b, the fifth being the '\0' which overwrites a[0]. The first one being the '.', which intentionally is the NOT read by the format for a. You hence write beyond b (which is undefined behaviour and I should stop explaining right now....).
One of the possible behaviours of this UB is that the fifth read character for b is written beyond and into the first entry of a.

Beginner problem with printf and scanf in C

I have a problem with scanf() and printf() function in a snippet of code like this:
#include <stdio.h>
int main() {
int a;
int b;
int c;
scanf("%d %d", &a, &b);
while (c >= 2) {
c = a % b;
a = b;
b = c;
printf ("%d\n", c);
}
return 0;
}
What I expect to happen, and happens in my brother's Code::Block, is for the program to wait for input from stdin and then print to stdout the results, one per line, until it reaches the highest common divisor.
However, when I type it in vi and then compile it with gcc and run the program from my terminal, the program correctly takes the input but exit without returning anything to stdout.
If I comment out the scanf() line and hardcode any number to a and b variables, everything works as expected.
I'm trying to learn C and I've read basic documentation on the functions, but I can't help to understand this kind of behaviour.
I've tried to put a setbuf(stdout, NULL) before declaring variables but nothing changed.
Can somebody give me a clue?
There's nothing wrong with your scanf and printf calls but, as others have mentioned, one obvious problem is that you are testing the value of an uninitialised variable (c).
Maybe, what you want is a do { ... } while (...); loop, rather than a simple while loop.
The following code will guarantee to execute the loop at least once and then, at the end of each loop, check whether or not to repeat it:
#include <stdio.h>
int main() {
int a;
int b;
int c;
scanf ("%d %d", &a, &b);
do {
c = a % b;
a = b;
b = c;
printf ("%d\n", c);
} while (c >= 2);
return 0;
}
(Alternatively, initialise c with a value that is >= 2, i.e. use the declaration: int c = 3;.)
For further discussion of the do .. while loop, see here: 'do...while' vs. 'while'

Scanf continuous input in C

#include <stdio.h>
int main ()
{
double a=0;
char b=0;
scanf ("%d%c",&a,&b);
printf ("%d,%c", a, b);
return 0;
}
This is my code for a quick test program I wrote to play around with the scanf function in C. I am trying to have the user input something like 78X + 5 = 19 (then hit enter) and then parse that into variables a, b, and c where in this case a=78, b=5, c=19. In the sample code, when I type in 78X, c doesn't store a value to b and only prints "78, " and then terminates. Why won't it store a value to b?
If your input is 75x then below is the code which reads the value and stores it in a(75) and b(x) respectively
#include <stdio.h>
int main ()
{
int a=0;
char b=0;
scanf ("%d%c",&a,&b);
printf ("%d%c", a, b);
return 0;
}
The , in your format string is significant. The string %d,%c would match the input 78,x but it would not match 78x .
Also you need to use %f to scan and print a double. Using %d causes undefined behaviour (which may manifest itself as b seeming to not appear). Either change to %f, or change your double to an int.

how to convert char to int

I'm trying to write a short program were:
#include <stdio.h>
void main()
{
char=a,b,c;
printf("please place 3 numbers:\n");
scanf("%c%c%c", &a,&b,&c);
}
The exercise I'm trying to solve is how to change the char to int so if I write in a the number 3, I will get the number 3 Printed.
at this point I'm only getting the value.
I would appreciate any help.
The answer depends somewhat on what you can assume about the character set. If it's something like ASCII (or really, any character set that includes the digits in sequential order), you just need to offset the character value by the value of the character 0:
int aValue = a - '0';
I'm sure that C# provides better ways to do what you're trying to do, though. For example, see this question for some examples of converting strings to integer values.
First of all your syntax need some checking
You should know that you declare a variable this way (a char in this example):
char a;
If you want to declare multiple variables of the same type in a row you do :
char a, b, c;
If you want to assign a value to a declared variable :
a = '3';
Now to print a char using printf (man printf is a must read, more infos are in coreutils) :
printf("%c", a);
If you want to get the char from the command line, I recommand you to use getchar() (man getchar) instead of scanf because if suits better what you are trying to achieve and doesn't require you to use a syntax in scanf that I am sure you don't fully understand yet.
Your question is incredibly light on details, so here are several options:
#include <stdio.h>
int main()
{
char a,b,c;
printf("please place 3 numbers:\n");
scanf("%c%c%c", &a,&b,&c);
printf("Printing ints (auto-promotion): %d %d %d\n", a, b, c);
printf("Printing ints (explicit-promotion): %d %d %d\n", (int)a, (int)b, (int)c);
printf("Printing digits: %d %d %d\n", a-0x30, b-0x30, c-0x30);
return 0;
}
If the input is 123,
I expect the output to be:
Printing ints (auto-promotion): 49 50 51
Printing ints (explicit-promotion): 49 50 51
Printing digits: 1 2 3
Some things I fixed along the way.
main should return an int, not be void.
char=a,b,c; is a syntax error. You meant char a,b,c;
added a return 0; at the end of main.
You question is not quite understandable. Still I'll try to help. I think that what you want is to store an integer value in the char variable. You can do so by using the following code:
#include<stdio.h>
void main()
{
char a,b,c;
printf("Enter three numbers:\n");
scanf(" %c %c %c",&a,&b,&c); //notice the spaces between %c
}
Or if you want to enter a character and print its ASCII value, you can use the following code:
#include<stdio.h>
#include<conio.h>
void main()
{
char a,b,c;
printf("Enter three characters:\n");
scanf(" %c %c %c",&a,&b,&c);
printf("Entered values: %d %d %d",a,b,c);
getch();
}

Resources