how to convert char to int - c

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();
}

Related

Infinite for loop? ()in c

the value of i resets after it reachers 7
#include <stdio.h>
int main(){
char marks[10];
int i;
printf("enter the numbers:\n");
printf("-------------------\n");
for (i=0;i<10;i++)
{
printf("%d\n",i);
printf("element %d-",i);
scanf("%d", &marks[i]);
}
printf("\n all %d",marks);
printf("\n second %d\n",marks[1]);
return 0;
}
output
Problem is here:
scanf("%d", &marks[i]);
Specifier "%d" expects a pointer to int, not char. Usually it will write 4 bytes what is a typical size of int.
Therefore on 8th iteration the elements of marks at index from 7 to 10 are touched. However, marks[10] is outside of marks array (only indices 0-9) are valid. Undefined Behaviour is invoked and the program can do anything, from crashing to infinite looping or conjuring nasal deamons.
To fix the program change the type of marks to int:
int marks[10];
Note:
UB is invoked even on the first iteration because "%d" expects a pointer to int while type of &marks[0] is char*. This operation is undefined by C standard because int* and char* may differ in size and/or representation and/or alignment. However it is a unlikely case for modern CPUs.
You have declared the marks as a character array and tried to get input from user using %d which asks asks for an integer,
#include <stdio.h>
int main(){
int marks[10];
int i;
printf("enter the numbers:\n");
printf("-------------------\n");
for (i=0;i<10;i++)
{
printf("%d\n",i);
printf("element %d-",i);
scanf("%d", &marks[i]);
}
printf("\n all %d",marks);
printf("\n second %d\n",marks[1]);
return 0;
}
Also I didn't understand the use of all so I couldn't find a solution for it. If you want to print a specific number then you have to specify it like you have done it for second or if you want to display the total you want to add a furthermore code to calculate the sum of elements in the array.

Weird code interaction when scanning and printing chars in C

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);
}

scanf doesn't accept input

Only my first line of input request user to key in the value. Input B not request user to key in and shows wrong total.
#include <stdio.h>
#include <stdlib.h>
//BASIC CALCULATION INPUT 2 INTEGER ONE BY ONE
int main(int argc, char *argv[])
{
int a,b,c;
//REQUEST ONE INPUT
printf("Integer A: \n");
scanf("%a",&a);
//REQUEST ONE INPUT
printf("Integer B: \n");
scanf("%b",&b);
c=a+b;
//DISPLAY AMOUNT INTEGER
printf("Total: &c",c);
system("PAUSE");
return 0;
}
Your both scanf statements are wrong!
It should be
scanf ("%d",&a);
scanf ("%d",&b);
For taking user input a and b of type integer use %d.
&a is the reference (address) of identifer a which holds the value of a.
And also user output printf statement for integer c should be
printf("%d",c);
Add a space in the scanf to discard all whitespace before matching an integer. Such as a
scanf(" %b",&b);
^^^
space in the scanf
There is no format specifier like %b that's why Input B doesn't request user to key in.I think this this will help you.
#include <stdio.h>
#include <stdlib.h>
//BASIC CALCULATION INPUT 2 INTEGER ONE BY ONE
int main(int argc, char *argv[])
{
int a,b,c;
//REQUEST ONE INPUT
printf("Integer A: \n");
scanf("%d",&a);
//REQUEST ONE INPUT
printf("Integer B: \n");
scanf("%d",&b);
c=a+b;
//DISPLAY AMOUNT INTEGER
printf("Total: &c",c);
system("PAUSE");
return 0;
}
Both of your scanf statements use wrong format specifiers. Thus undefined behaviour.
scanf("%a",&a);
and
scanf("%b",&b);
a expects a float*as its argument, but you are passingint*. There's no format specifierb` in standard C either.
Use %d to scan int's.
Better yet, avoid scanf altogether and use fgets and parse the line instead.
Another problem is your printf statement:
printf("Total: &c",c);
is wrong too. It should be:
printf("Total: %c",c);
to print the value of c.

"static char" vs. "char" in C

To practice variable declaration, placeholders and I/O calls, I did a sample assignment in the book that I am using to study. However, I keep running into a particular problem, in that when I try to declare more than one character variable for the purpose of input, even if the compiler doesn't catch any syntax error, the program when executing will only return one character variable. This is the code in question:
#include <stdio.h>
int main()
{
double penny=0.01;
double nickel=0.05;
double dime=0.1;
double quarter=0.25;
double value_of_pennies;
double value_of_nickels;
double value_of_dimes;
double value_of_quarters;
double TOTAL;
int P;
int N;
int D;
int Q;
char a,b;
//used "static char" instead of "char", as only using the "char" type caused a formatting error where only the latter character entered in its input would appear
printf("Please enter initials> \n");
printf("First initial> \n");
scanf("%s", &a);
printf("Second initial> \n");
scanf("%s", &b);
//"%s" was used as the input placeholder for type "char"
printf("%c.%c., please enter the quantities of each type of the following coins.\n", a, b);
printf("Number of quarters> \n");
scanf("%d", &Q);
printf("Number of dimes> \n");
scanf("%d", &D);
printf("Number of nickels> \n");
scanf("%d", &N);
printf("Number of pennies> \n");
scanf("%d", &P);
printf("Okay, so you have: %d quarters, %d dimes, %d nickels, and %d pennies.\n", Q, D, N, P);
value_of_pennies=penny*P;
value_of_nickels=nickel*N;
value_of_dimes=dime*D;
value_of_quarters=quarter*Q;
TOTAL=value_of_quarters+value_of_dimes+value_of_nickels+value_of_pennies;
printf("The total value of the inserted coins is $%.2lf. Thank you.\n", TOTAL);
//total field width omitted as to not print out any leading spaces
return(0);
}
And this is the transcribed output ("a", "e", and the four "1"s are sample arbitrary input values:
Please enter initials>
First initial>
a
Second initial>
e
.e., please enter the quantities of each type of the following coins.
Number of quarters>
1
Number of dimes>
1
Number of nickels>
1
Number of pennies>
1
Okay, so you have: 1 quarters, 1 dimes, 1 nickels, and 1 pennies.
The total value of the inserted coins is $0.41. Thank you.
I entered the characters "a" and "e" as input values for the char variables "a" and "b", but only "e" had shown up. On the other hand, should I have put a "static" in the "char" variable declaration, both inputted char values will be displayed in the relevant print call.
For future reference, I would like to ask about why such a thing would occur the way that it did, and the value of the "static" word in the declaration.
(As an aside, I am aware that I could have simply made the "value_of_(insert coin here)" variables as constant macros.)
With a definition like
char a,b;
writing a statement like
scanf("%s", &a);
scanf("%s", &b);
invokes undefined behaviour. %s is not a format specifier for a char. Using wrong format specifier can and will lead to UB. You should use %c to scan a char.
To elaboreate,
%s format specifier expects a corresponding argument which is a pointer to char array. It scans multiple characters until it encounters a space (whitespace character, to be pedantic) or newline or EOF.
%c format specifier expects a corresponding argument which is a pointer to char variable. It reads only one char from the input buffer.
So, with %s, if you supply the adress of a char variable, it will try to access beyond the allocated memory region for writing the scanned data, which will invoke UB.
You may want to read some more on printf(), scanf() and format specifiers before moving forward.
You have used the wrong format specifier for char. char uses %c not %s. As far as static goes, I'm a bit confused about your question. You say in a comment that you are using static char, but I do not see any variables declared as static char.

Extract integer from a random array

I have as input integer,cahr,symbol random array. I want to extract only integers from that array.
For example: input is [#56gY68#$&*+7j^78gu5];
output is 56 68 7 78 5
Here is my code:
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
#include<ctype.h>
void main()
{
char arr[10];
int arr1[10],i;
clrscr();
for(i=0;i<10;i++)
{
scanf("%s",arr[i]);
}
for(i=0;i<10;i++){
if(isdigit(arr[i])){
arr1[i]=arr[i];
}
}
for(i=0;i<10;i++){
printf("%d",arr1[i]);
}
getch();
}
The code fails to extract an integer. What do I need to change?
The code shown here invokes undefined behaviour. The problems in your code:
scanf() requires a pointer type argument to store the scanned value.
%s is for strings, %c is for char.
for %c, the \n is not ignored. So, you've to use it like " %c" to avoid the trailing newline.
However, I don't see any logic to "extract only one integer from a random array". You may need to check your logic once again.
Notes:
The recommended signature of main() is int main(void).
always initalize all your local variables.

Resources