I am new to C and memory allocation. I am trying to take a 12 digit input and save as int so later on I can do some calculations. So far I have:
#include <stdio.h>
void main(void){
char number[12];
do
{
printf("Credit Card Number: ");
scanf("%lli", number);
} while (number == 1);
printf("%lli", number);
}
Right now I use long long int since I can use 64 bits, but when I run it and type in 123 I get:
27583791809822484
Could someone explain what I am doing wrong, why the output is 27583791809822484 and if I have any styling errors.
scanf %lli expects a pointer to a long long int. You provided a pointer to an array of 12 char.
printf %lli expects a long long int. You provide a pointer.
long long int card_num;
scanf("%lli", &card_num);
printf("%lli", card_num);
If you wanted to portable code, you'd use
#include <stdint.h>
#include <inttypes.h>
uint64_t card_num;
scanf("%" SCNu64, &card_num);
printf("%" PRIu64, card_num);
If you wanted to store the number as a string (which is quite reasonable for a credit card number), then char number[12] makes sense, but you'd use %s. Actually, it would have to be char number[13] to be large enough to store 12 digits and the trailing NUL.
char card_num[13];
scanf("%12s", card_num);
printf("%s", card_num);
#include <stdio.h>
void main(void){
long long int creditcard;
printf("Credit Card Number: ");
scanf("%lli", &creditcard);
printf("%lli", creditcard);
}
this will work.
EDIT: As stated in the comments, if you have leading zeros, this won't work. Instead taking it as string like above is better.
Related
When you declare two variables char a,b; and then you use first 'a' and then 'b',it prints only b, but if you declare it 'b' then 'a', it has no problem printing both in ASCII,the point of the program is to read 121 and 120 and to print yx. the problem - https://prnt.sc/pr5nww
and if you swap them -https://prnt.sc/pr5mt5
#include <stdio.h>
#include <stdlib.h>
int main(){
char a,b;
scanf("%d",&a);
scanf("%d",&b);
printf("%c",a);
printf("%c",b);
}
This is kind of a confusing situation. When it comes to mixing char and int values (as you might do when investigating the numeric values of characters in a character set), it turns out the rules for scanf and printf are almost completely different.
First let's look at the scanf lines:
char a,b;
scanf("%d",&a);
scanf("%d",&b);
This is, in a word, wrong. The %d format in scanf is for scanning int values only. You cannot use %d to input a value of type char. If you want to input a character, the format for that is %c (although it'll input it as a character, not a number).
So you'd need to change this to
char a,b;
scanf("%c",&a);
scanf("%c",&b);
Now you can type characters like A and $ and 3 and have them read into your char variables a and b. (Actually, you're going to have additional problems if you hit the Return key between typing the characters for a and b, but that's a different story.)
When it comes to printing the characters out, you have a little more freedom. Your lines
printf("%c",a);
printf("%c",b);
are fine. And if you wanted to see the integer character-set values associated with the characters, you could have typed
printf("%d",a);
printf("%d",b);
and that would have worked, too. This is because when you call printf (and other functions ike it), there are some automatic conversions that take place: types char and short int are automatically promoted to (passed as) int, and type float is promoted to double. But these automatic conversions happen only for values of those types (as when calling printf). There a=is no such conversion when you're passing pointers to these types, as when calling scanf.
What if you wanted to read numbers, not characters? That is, what if you wanted to input the number 65 and see it get printed as capital A? There are several possible ways to do that.
The first way would be to continue to use %d in your scanf call, but change the type of your variables to int:
int a,b;
scanf("%d",&a);
scanf("%d",&b);
Now you can print a and b out using either %c or %d, and it'll work fine.
You could also use a temporary int variable, before reassigning to char, like this:
char a,b;
int tmp
scanf("%d",&tmp);
a = tmp;
scanf("%d",&tmp);
b = tmp;
The final, lesser-known and somewhat more obscure way, is to use the h modifier. If you say
char a,b;
scanf("%hhd",&a);
scanf("%hhd",&b);
now you're telling scanf, "I want to read decimal digits, but the target variable is a char, not an int."
And, again, you can print a and b out using either %c or %d, and it'll work fine.
the point of the program is to read 121 and 120 and to print yx
Do
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
char a, b;
/* Scan into the half of the half of an int (the leading blank
makes scanf() eat whitespaces): */
scanf(" %hhd", &a);
scanf(" %hhd", &b);
/* Print the half of the half of an int: */
printf("%hhd", a);
printf("%hhd", b);
}
To print the characters literally do the printing part like this:
...
printf("%c", a);
printf("%c", b);
}
I tried to read 2 variables from the keyboard and to write them on the screen and I have a problem, the program display me only one..
#include <stdio.h>
#include <stdlib.h>
int main()
{
short int n,x;
scanf("%d",&n);
scanf("%d",&x);
printf("%d %d",n,x);
return 0;
}
I introduced 14 and 15 and the program return me 0 and 15
can somebody tell me why?
Use %hd format specifier for short int
Use %hu format specifier for unsigned int
Use %d format specifier for int
Use %ld format specifier for long int
#include <stdio.h>
#include <stdlib.h>
int main() {
short int n, x;
scanf("%hd", &n); // Notice %hd instead of %d for short int
scanf("%hd", &x); // Notice %hd instead of %d for short int
printf("%hd%hd", n, x);// Notice %hd instead of %d for short int
return 0;
}
%d assumes the variable to be of data type int.
Use the data type int:
int main()
{
int n,x;
scanf("%d",&n);
scanf("%d",&x);
printf("%d %d",n,x);
return 0;
}
or use %hd instead of %d
int main()
{
short int n,x;
scanf("%hd",&n);
scanf("%hd",&x);
printf("%hd %hd",n,x);
return 0;
}
Note, scanf("%d",&x); read a value and stores it to the memory addressed by &x. Since &x is treated as a 4 byte memory, 4 bytes are written to the address specified by &x.
The formatters in scanf() and printf() doesn't match the type of your variables n and x.
%d uses the variables as they were int while int has probably the double number of bytes as short int. (Integer types)
Hence, with the wrong formatters, scanf() uses the provided addresses wrong.
For printf() it's a bit more complicated: The short ints are converted to int internally. (Default argument promotions) Hence, printing short int with %d (as they were int) doesn't fail.
So, it's the scanf() what must be fixed.
Either use correct formatters:
#include <stdio.h>
int main()
{
short int n,x;
scanf("%hd",&n);
scanf("%hd",&x);
printf("%d %d",n,x);
return 0;
}
Live Demo on ideone
or use correct variable type for the formatters:
#include <stdio.h>
int main()
{
int n,x;
scanf("%d",&n);
scanf("%d",&x);
printf("%d %d",n,x);
return 0;
}
Live Demo on ideone
The formatting of scanf() and printf() families are very powerful and flexible but unfortunately very error-prone as well. Using them wrong introduces Undefined Behavior. The compiler is (usually) unable to recognize errors as the evaluation of formatters happens at run-time and inside the scanf()/printf() functions. So, they have to be used caaarefully.
I am a beginner. I want to write a program, that will guess a number, which user picked. In general, user pick a number within the given limit, the program will generate a random number within same limit, ask user if it's a right number, Y/N answer, program reads it, then ask if user's number is bigger or smaller, reads the answer and pass this information to 2 additional functions.
(I didn't finish those yet, but the idea is that it will divide the rest of numbers in 2, ask again, bigger smaller, divide it once again by 2 and so on, till we get the answer.)
The problem is, that even if I use a simplest array of type char, I cannot get it work. The answer of the computer is if I didn't book enough memory for one of the arrays.
I'm still 2 chapters away from the arrays theme in my book, I just wanted to write this program. What I use here is what I've learned so far, so if it's possible, don't use any more complex functions and features of C in your answers.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
#include <time.h>
int bigger(int number, int limit);
int lower(int number, int limit);
int main(void) {
system("COLOR B0");
const int Hlimit=100;
const int Llimit=0;
char alowwed_answer[]={'>','<'};
char answer[2];
char alowwed_answerYN[]={'Y', 'N'};
char answerYN[2];
srand((unsigned)time(NULL));
int numberTOguess;
printf("\r\nEnter your number from %i to %i, "
"and I will try to guess!: ",Llimit,Hlimit);
while(scanf("%i",&numberTOguess) )
{
int check=rand()%Hlimit;
printf("\r\nyour number is - %i Y/N?",check);
scanf("%c",&answerYN[0]);
printf("answer is %c\r\n", answerYN);//this line is for checking;
int check_answ=strcmp(answerYN[0],alowwed_answerYN[0]);
printf("check answer is %i",check_answ);//this line is for checking;
if(check_answ==0)
{
printf("I did it!");
break;
}
else if(strcmp(answerYN[0],alowwed_answerYN[1])==0)
{
printf("\r\nyour number is bigger '>' or smaller '<'?: ");
scanf("%c",&answer);
if(strcmp(answer[0],alowwed_answer[0])==0)
{
bigger(check, Hlimit);
}
else if(strcmp(answer[0],alowwed_answer[1])==0)
{
lower(check, Llimit);
}
}
}
printf("\r\nI did it!");
return 0;
}
int bigger(int number, int limit)
{
printf("it is bigger!");//I will finish this part as soon as I will get first part working.
return 0;
}
int lower(int number, int limit)
{
printf("it is lower!!!");//I will finish this part as soon as I will get first part working.
return 0;
}
Update
Thanks, I took your advice and change the statement type to SWITCH. But it still doesn't work properly. Somehow, nested switch doesn't function at all.
Look at the code:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
#include <time.h>
int bigger(int number, int limit);
int lower(int number, int limit);
int main(void) {
system("COLOR B0");
const int Hlimit=100;
const int Llimit=0;
char answerBL;
char answerYN;
srand((unsigned)time(NULL));
int numberTOguess;
printf("\r\nEnter your number from %i to %i, "
"and I will try to guess!: ",Llimit,Hlimit);
while(scanf("%i",&numberTOguess) )
{
int check=rand()%Hlimit;
printf("\r\nyour number is - %i Y/N?",check);
scanf("%c",&answerYN);
switch(answerYN)
{
case 'Y':
printf("I did it!");
break;
case 'N':
printf("\r\nOk, your number is bigger '>' or smaller '<'?: ");
scanf("%c",&answerBL);
switch(answerBL)
{
case '>':
bigger(check, Hlimit);
break;
case'<':
lower(check, Llimit);
break;
}
default:
printf("Y or N?");
}
}
printf("\r\nEND!");
return 0;
}
int bigger(int number, int limit)
{
printf("it is bigger!");
return 0;
}
int lower(int number, int limit)
{
printf("it is lower!!!");
return 0;
}
Edit
Problem is solved, I found the reason and how to fix it. Here it is, from another topic
The basic problem is that scanf() leaves the newline after the number in the buffer, and then reads it with %c on the next pass. Actually, this is a good demonstration of why I don't use scanf(); I use a line reader (fgets(), for example) and sscanf(). It is easier to control.
You can probably rescue it by using " %c" instead of "%c" for the format string. The blank causes scanf() to skip white space (including newlines) before reading the character.
But it will be easier in the long run to give up scanf() and fscanf() and use fgets() or equivalent plus sscanf(). All else apart, error reporting is much easier when you have the whole string to work with, not the driblets left behind by scanf() after it fails.
You should also, always, check that you get a value converted from scanf(). Input fails — routinely and horribly. Don't let it wreck your program because you didn't check.
answered Mar 5 '12 at 7:05
Jonathan Leffler
The function strcmp expected two pointers as arguments, pointers to the first characters of a null-terminated byte strings.
With e.g.
strcmp(answerYN[0],alowwed_answerYN[0]);
you have two major problems:
The array answerYN is (partially) uninitialized, its contents is (also partially) indeterminate. That means answerYN[1] is likely not the string terminator as needed.
alowwed_answerYN[0] is a single char not a pointer to a string. This should have given you a warning about invalid conversions or similar.
If you just want to compare characters, use normal comparison for equality ==, as in answerYN[0] == alowwed_answerYN[0].
Or why not skip alowwed_answerYN completely and plainly use the explicit character literal as in answerYN[0] == 'Y'. That's even clearer than using an array for the 'Y' and 'N'.
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 */
I'm here trying to convert 4-digit hexa into dec but didn't succeed.
Here is a my code.
unsigned int array[4];
printf("Type in 4-digit hexa: \n");
scanf("%x", &array);
while(getchar() != '\n');
printf("Your number in dec is %u \n", array);
I don't know what's wrong with it but it just wouldn't give out the correct dec output.
Like when I put in EEFF, it's supposed to give out 61183 but the program kept on printing out 65518.
Where's this number from? What's wrong with my code? I used unsigned int according to my consideration that FFFF is equals to 65385 and the range for unsigned int is 0 to 65535. There should be no problem with the range of data and I also used %u with it.
The only thing I can think of right now after I've done some searching is that this problem might has sth to do with the size of unsigned int to int or sth.
I read the explanation but didn't quite understand.
I know, this might be a duplication but I'm here asking for an easier explanation
of why this doesn't work. To be honest, I'm an absolutely newby for both this site and programming so please go easy on me with the coding. FYI, I don't really know anything outside of stdio.h .
You are passing a pointer, array, to printf(). There is no need for an array here, what you're trying to scan and print is a single number.
unsigned int number;
printf("Type in 4-digit hex:\n");
if (scanf("%x", &number) == 1)
printf("Your number in dec is %u \n", number);
Also note that it's considered a good idea to check if scanf() succeeds or not, by inspecting the return value.
You don't need an array for that:
unsigned int val;
printf("Type in 4-digit hexa: \n");
scanf("%x", &val);
printf("Your number in dec is %u \n", val);
a. print array[0], not array.
(optional) b. scan to array, not to &array.
c. what is the point of the getchar()?
No, you must input as string to a point of characters. After that, you convert to number.
Ex
char *str=char[10];
int i=0,num=0;
printf("Type in 4-digit hexa: ");
scanf("%s",str);
for(i=0;str[i]!='\0';i++)
if(str[i]>='0' && str[i]<='9') num=16*num+str[i]-'0';
else if(str[i]>='a' && str[i]<='f') num=16*num+str[i]-'a';
else if(str[i]>='A' && str[i]<='F') num=16*num+str[i]-'A';
printf("Dec is %d",num);