different output is generated every time I run the code - c

Here in this code, when I execute it, it sometimes display correct value of nT and nF, sometimes it display correct nF but incorrect nT(i.e 0).
Why is it so??
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main()
{
unsigned char nT,nF;
puts("Enter No. of Testcases & Faults");
scanf(" %hhu %hhu",&nT,&nF);
printf("\n %hhu %hhu",nT,nF);
}

You need to use %hhu as the format specifier for an unsigned char. (Obscure I know: one for the pub quiz.) Also, you might want to introduce some spaces between your formatters:
int read = scanf("%hhu %hhu %s", &nT, &nF, extension);
Currently the behaviour of your program is undefined.
Prior to C99 you're pretty much at the mercy of your compiler.
Further notes:
Always check the return value of scanf which gives you useful information about the number of inputs that are read successfully.
extension is only good for 4 characters plus the nul-terminator.

Related

Unexpected behaviour while taking input in C language

I am trying to run this code which seems fine to me but the end results are not much convincing. Here's the code:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main()
{
unsigned char nT,nF;
char extension[5];
puts("Enter No. of Testcases & Faults");
scanf("%d %d %s", &nT, &nF, extension);
printf("%d %d\n",nT,nF);
getch();
}
Below is the sample input:
Enter No. of Testcases & Faults
50 50 code
Below is the output:
0 50
Below is the Expected output:
50 50
Note: I am bounded to use unsigned char and cannot use unsigned int.
I am using DevCpp 4.9.9.2. Please help if anyone has got the solution or the reason for why this is happening.
Look into your scanf clause. You are passing two (pointers to) unsigned char variables to it, yet declare that you are reading two ints in your format specifier (%d specifier). Pass %hhu if you want to read unsigned char.
When you pass &extension to scanf there is no need to use ampersand. The name of the array gets converted to the pointer to its first element, so it's sufficient to pass just extension.
You are also using a very old IDE (Dev-C++), that is no longer developed. Probably the underlying compiler is dated as well. I advise to use newer tools, Code::Blocks is actively developed, quite newbie-friendly and similar to Dev-C++ to a certain extent.
However, on Windows platforms, the MSVCRT library does not support the %hhu format specifier, as has been noted in this question. MingGW compiler relies on this implementation, so it does not support %hhu on windows as well. Cygwin is a project that simulates Linux environment on Windows and is distributed with its own version of C library, that supports, among other things, %hhu. As a sidenote, you can configure Code::Blocks to work with Cygwin (as described here). I don't know if the same can be achieved with Dev-C++.
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main()
{
unsigned int nT,nF;
char extension[5];
puts("Enter No. of Testcases & Faults");
scanf("%d %d %s", &nT, &nF, extension);
printf("%d %d\n",nT,nF);
getch();
}
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main()
{
unsigned char nT,nF;
char extension[5];
puts("Enter No. of Testcases & Faults");
scanf("%hhu %hhu %s", &nT, &nF, extension);
printf("%hhu %hhu\n",nT,nF);
// getch();
}
You can see output on below image

C - how to read input from text file to 2D array [duplicate]

Suppose,"5181 2710 9900 0012"- is a string of digits.I need to take one single digit at a time as input from the string of number without space to make arithmatic operations . So, i write that,
int a[20];
for(int i=0;i<16;i++)
{
scanf("%d",&a[i]);
}
but it didn't give me expected result. But when i use "%1d"instead of "%d",it gave me the expected result. so, how it works?
Since scanf is the inverse of printf, you could verify this by printing any number with the modifier (just a little tip).*
In general, the number before the format is a 'width' modifier. In this case it means you're only reading one byte into a number. If you specify %d, it may be a number of arbitrary length.
Example:
#include <stdio.h>
int main() {
int a;
sscanf("1234", "%d", &a);
printf("%d\n", a); // prints 1234
sscanf("1234", "%1d", &a);
printf("%d\n"m a); // prints 1
}
*) this appears to be false for this particular case. Makes sense that numbers are not truncated when specifiying a %d format, though, since that would change the meaning of the number. However, for many cases you could try what printf would do to predict scanf's behavior. But of course, reading the manual or docs on it is always the more helpful approach :)

How to take one character at a time as input from a string of characters without space in c?

Suppose,"5181 2710 9900 0012"- is a string of digits.I need to take one single digit at a time as input from the string of number without space to make arithmatic operations . So, i write that,
int a[20];
for(int i=0;i<16;i++)
{
scanf("%d",&a[i]);
}
but it didn't give me expected result. But when i use "%1d"instead of "%d",it gave me the expected result. so, how it works?
Since scanf is the inverse of printf, you could verify this by printing any number with the modifier (just a little tip).*
In general, the number before the format is a 'width' modifier. In this case it means you're only reading one byte into a number. If you specify %d, it may be a number of arbitrary length.
Example:
#include <stdio.h>
int main() {
int a;
sscanf("1234", "%d", &a);
printf("%d\n", a); // prints 1234
sscanf("1234", "%1d", &a);
printf("%d\n"m a); // prints 1
}
*) this appears to be false for this particular case. Makes sense that numbers are not truncated when specifiying a %d format, though, since that would change the meaning of the number. However, for many cases you could try what printf would do to predict scanf's behavior. But of course, reading the manual or docs on it is always the more helpful approach :)

Can scanf() store values?

Hi I am now learning the C language and I have a little problem with a exercise of the book I read. My code is this:
#include<stdio.h>
int main()
{
unsigned char one=0;
unsigned char two=0;
printf("Quantity 1 = ");
scanf("%d",&one);
printf("Quantity 2 = ");
scanf("%d",&two);
printf("The value is %d",one);
return 0;
}
Why when I am trying to see the value of one the initial value appears and not the value after the scanf?
You need to use int type in conjuction with %d specifier, and char with %c specifier. And %u with unsigned integers.
#include<stdio.h>
int main()
{
unsigned int one=0; unsigned int two=0;
printf("Quantity 1 = ");scanf("%u",&one);
printf("Quantity 2 = ");scanf("%u",&two);
printf("The value is %u",one);
return 0;
}
Basicaly, scanf will try to read integer from input and it will try to store it inside memory location that is not large enough, so you will have undefined behavior.
You can find good reference here.
However, if you try to use character for an input type, you may want ask yourself why you won't get a chance to enter a second Quantity (if you type 4 and press enter). This is because second scanf will read enter key as a character. Also, if you try to type 21 (for a twentyone), it will fill the first value with 2 and second with 1 (well, with their ASCII values).
So, be careful - be sure that you always choose the right type for your variables.
Never use scanf.
Never use scanf.
Seriously, never use scanf.
Use fgets (or getline, if you have it) to read an entire line of input from the user, then convert strings to numbers with strtol or its relatives strtod and strtoul. strsep may also be useful.
Check if scanf() is working properly by reading its return value. For quickstart, read the details about scanf() at this link.
What you are doing is inputting a integer using "%d" into an unsigned char variable, therefore scanf() may not be working as it should.
Change
unsigned char one=0; unsigned char two=0;
to
unsigned int one=0; unsigned int two=0;
and also use %u instead of %d then it will print the value after scanf().
You declared the variable one to be a char:
unsigned char one=0;
But then you told scanf to read an int:
scanf("%d",&one); /* %d means int */
Int is bigger than char (typically 4-bytes vs. 1-byte), causing the problem you describe.
Change your scanf to:
scanf("%c",&one); /* %c means char */
Then when you print out the value, also print a char:
printf("The value is %c",one); /* %c means char */

Why is %hd necessary in scanf?

I created a very simple progam whith a menu,
that take a value, then memorize it into the
local variable value, and finally with the
second option the progam prints the value.
my question is:
Why does the program work only if I add an "h"
to the scanf parameter?
In other words: what kind of relation there is
between scanf() and my local int value variable?
thanks!
p.S. (I used Dev-C++ (GCC) to compile it.
With Visual Studio it works)
#include <stdio.h>
main () {
int value = 0;
short choice = 0;
do {
printf("\nYour Choice ---> ");
scanf("%d", &choice); /* replace with "%hd" and it works */
switch (choice) {
case 1:
printf("\nEnter a volue to store ");
scanf("%d", &value);
getchar();
printf("\nValue: %d", value);
break;
case 2:
printf("\nValue: %d", value);
break;
}
} while (choice < 3);
getchar();
}
With scanf, the "h" modifier indicates that it's reading a short integer, which your variable choice just happens to be. So the "%hd" is necessary to write only two bytes (on most machines) instead of the 4 bytes that "%d" writes.
For more info, see this reference page on scanf
The variable choice is of type short so that's why you need the %h specifier in scanf to read into it (in fact you don't need the d here). The int type just requires %d. See the notes on conversions here
You're reading into a short. The h is necessary because %d is the size of an int by default. See this reference page on scanf.
It looks like your problem is that choice is a short, which is (generally) 2 bytes long, while %d expects an integer, which is (generally) 4 bytes long… So the scanf clobbers whatever comes after choice on the stack.
choice is a short and %d specifies an int.
When you specify %d, scanf has to assume that the associated argument is a pointer to an int sized block of memory, and will write an int to it. When that happens it will likely be writing to data adjacent to but not part of choice and the results are undefined and probably not good! If it works in one compiler and not another that is simply the nature of undefined behaviour!
In GCC -Wformat should give you a warning when you make this error.
From the comp.lang.c FAQ:
Why doesn't the code short int s; scanf("%d", &s); work?
Someone told me it was wrong to use %lf with printf. How can printf use %f for type double, if scanf requires %lf?
%d is for reading an int, not a short. Your code never really "worked" -- it just appears that in this case you didn't notice any difference between what you wanted and the undefined behavior you got.
The modifier for scanf to input a variable of type short is %hd. Hence you need to specify the correct modifier.
scanf("%d",&integer); // For integer type
scanf("%hd",&short_int); // For short type
Hence it doesnt work.
Depending upon numeric padding, endian-ness, and other such issues, you may be storing either the upper or lower part of the input value into choice; you are storing the rest of the input value into memory that may or may not be being used for anything else.

Resources