Answer the question
In order to leave comments, you need to log in
How to extract the first character, the second character, etc. from a variable in C, and from what type of variable is it most convenient to do this?
In general, the goal is this: the user enters a 4-digit number, the program adds the first two numbers and the first last numbers and writes them to a variable.
for example, the user entered 1645, then one variable will be equal to 1+6=7, the second variable 4+5=9 The
question is: how to extract the first character from the variable, the second, etc.? And what is the easiest way to do this?
I write in C, a program without an interface (looks like a command line). I know how to do it in the usual C++Builder, but there were problems. I write in Code Blocks
Answer the question
In order to leave comments, you need to log in
#include <stdio.h>
int main(void)
{
char s[4] = "1234";
printf("%d\n", (s[0] - '0') + (s[1] - '0'));
printf("%d\n", (s[2] - '0') + (s[3] - '0'));
return 0;
}
[[email protected] c]$ .ansi t.c -o t
[[email protected] c]$ ./t
3
7
[[email protected] c]$
All the same, a string is entered, and pull out the numbers from it. Then convert them to int via atoi().
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question