For my first task I am using fgets() to read a string from stdin. So I input 1234567890 on the terminal and it stores the string into a variable called str. Now I want to split the digits up and perform addition. In this case the sum would be 55 since 1+2+3+4+5+6+7+8+9+0 = 55.
How can I do that?
My code so far
#include <stdio.h>
#include <string.h>
int main(void){
char str[100];
printf("Please enter the 10 digit number \n");
fgets(str, 10, stdin);
//Separate the digits
//calculate their sum
int sum =..............
//print out the sum
printf("the sum of the digits is: %s", sum);
return(0);
}
Approach 1:
If you know for sure that you're counting for single digit integer, you can use
array indexing to read the digit-by-digit value from the input string.
convert the char value to corresponding int as per the required encoding (mostly, ASCII).
define one int variable , say res to hold the sum. perform the addition and store the result to sum.
loop untill terminating null is reached.
print out the sum using %d format specifier.
Approach 2:
Alternatively, you can do something like (again assuming,single digit integer)
Convert the whole string to integer using strtol(). You must check for the errors in that case.
define one int variable , say res to hold the sum.
perform modulo 10 (%0) on the converted interger value to take out the last digit. add and store that inres`
divide converted interger value by 10 (p /= 10).
continue to step 2 untill the result is 0.
when the converted interger value becomes 0, print the res.
P.S - Just FYI, usual way of splitting a string based on some delimiter is to use strtok().
Since you are sure the string will contain digits, subtract each character from '0' to get their numeric value.
int sum = 0;
fgets(str, sizeof str, stdin);
char *s = &str;
while(*s != '\0') {
sum += *(s++) - '0';
}
printf("the sum of the digits is: %d", sum);
First, make sure that you read only digits by using scanf, like this:
char str[11]; // 10 digits plus \0 terminator
printf("Please enter the 10 digit number \n");
scanf("%10[0-9]", str);
Now you can go through the digits one by one by indexing into str, and subtracting the code of digit zero, like this:
int nextDigit = str[i] - '0';
This should be enough information for you to complete the solution by adding a for loop around it. Make sure that you print sum using %d, not %s like you did in your code sample.
Related
Trying to input a 2 digit number e.g '35' and have the output return '53', however, my code makes it so that the output is '5335' rather than just '53' im completely lost and have been hunting for previous answers for hours to no success.
#include <stdio.h>
int main (void) {
char input[2];
char output[2];
int length;
printf("Enter a two-digit positive integer: ");
scanf("%s", input);
length = sizeof(input);
int x = 0;
while(length >=0) {
length--;
output[x]=input[length];
printf("%s", output);
x++;
}
printf("The reversed number is: %s", output);
return 0 ;
}
There are multiple things that needs to be changed in the code.
The char array length must be 3 in this case as your char ararys are supposed to store 2 characters. (One extra character for the null-terminating character '\0')
The length variable will store the number of bytes occupied by the character array but not the number of characters in the array. You might consider doing
length = sizeof(input)/sizeof(char)
Doing the modifications as mentioned in 1st and 2nd points will still result in an invalid result because the first thing you are appending to the input is the last character which will be '\0' and the output will always be an empty string. You should start appending from the 2nd last character of the input string and finally append a null-terminating character in the output.
Note:- It would be great if you can brush up on your knowledge of fundamental concepts of C.
what happens if I read an integer like 20,30,10000...9999 into variable a ? it only prints the first digit in the number that I've read...why is that ?
for example if I read 123, on the screen it prints 1. Isn't it supposed to convert the integer 123 into it's equivalent ASCII character representation ?
#include <stdio.h>
int main() {
char a;
scanf("%c", &a);
printf("%c", a);
return 0;
}
This is an exam question from C language.
No, it reads the character, which is represented by the machine as a small integer, into the variable.
If you enter 100 (the number 100, three keypresses and thus three characters), it will only store the first character of that, i.e. the leading 1.
If you wanted to convert a number to an actual integer, you should use %d and an int variable of course.
Printing with %c will print back a single character, by interpreting the small integer value as a character (rather than as an integer). So for an input of 100 you will see 1 printed back out, i.e. the character that represents the decimal digit one.
If you want to print out the numeric representation of the character you read in, scan with %c but print with %d, and cast the char to (int) in the printf() call.
The problem is that %c parse a char for console input. From a number like 123 it take only the first letter and dispose the rest. The way to parse a int value is using %d on the scanf function.
No, it will read only the first character into the char variable. How can a char variable store more than one character at an instant? It can't.
So if you want the ASCII value, input as an integer instead.
int a;
scanf("%d", &a); // suppose input is 65
printf("%c", a); // prints 'A'
printf("%d", a); // prints 65
Whereas
char a;
scanf("%c", &a); // suppose input is 65
printf("%c", a); // prints '6'
printf("%d", a); // prints 54 which is the ASCII value of '6'
I'm having trouble making this exercise for C-programming. I need to use the getchar()-method instead of the scanf(). When I use the scanf, everything works perfect when I type for instance 7. However when I use the getchar() and type 7, I will get the ASCII-code of 7, not the int 7. How do I fix this?
#include <stdio.h>
#include <stdlib.h>
int main(void) {
int i;
printf("Voer een getal in:\n");
fflush(stdout);
i = getchar();
//scanf("%d", &i);
if (i > -1000 && i < +1000) {
printf("het ingevoerde getal is: %d\n", i);
} else {
printf("foutieve invoer\n");
}
return EXIT_SUCCESS;
}
This is the correct behavior of getchar. While scanf's %d format specifier converts a sequence of digits to a decimal number, with getchar you need to do it yourself.
In order to do that, you need to know three things:
When the sequence of digits ends,
How to convert an ASCII code of a digit to a number, and
How to combine multiple digits into a single number.
Here are the answers:
You can decide to end the character input when the value returned by getchar is not a digit. You can use the isdigit function for that (include <ctype.h> header to use it).
You can convert a single digit character to its corresponding numeric value by subtracting the code of zero (i.e. '0') from the value returned by getchar
You can combine multiple digits into a number by starting the partial result at zero, and then multiplying it by ten, and adding the value of the next digit to it.
int num = 0;
for (;;) {
int ch = getchar();
if (!isdigit(ch)) break;
num = 10 * num + (ch - '0');
}
I want to type in a number that is 10 digits long, then put the digits into an array. But for some reason, I get this random 2-digit numbers that seem to have nothing to do with my input (??).
char number[10]; //number containing 10 digits
scanf("%s",number); //store digits of number
printf("%d\n",number[0]); //print the 1st digit in the number
printf("%d\n",number[1]); //print the 2nd digit in the number
Here is what I got:
Input:
1234567890
Output:
49
50
Actually, 49 should be 1, and 50 should be 2.
You are getting ASCII value of characters 1 and 2. Use %c specifier to print the digits.
printf("%c\n",number[0]);
Warning! Your code may invoke undefined behaviour!
But we'll talk about it later. Let us address your actual question first.
Here is a step by step explanation of what is going on. The first thing you need to know is that every character literal in C is actually an integer for the compiler.
Try this code.
#include <stdio.h>
int main()
{
printf("%d\n", sizeof '1');
return 0;
}
The output is:
4
This shows that the character literal '1' is represented as 4 byte integer by the compiler. Now, let us see what this 4 byte integer for '1' is using the next code here.
#include <stdio.h>
int main()
{
int a = '1';
printf("a when intepreted as int : %d\n", a);
printf("a when intepreted as char: %c\n", a);
return 0;
}
Compile it and run it. You'll see this output.
a when intepreted as int : 49
a when intepreted as char: 1
What do we learn?
The character '1' is represented as the integer 49 on my system. This is so for your system too. That's because in my system as well as yours, the compiler is using ASCII codes for the integers where '1' is 49, '2' is 50, 'A' is 65, 'B' is 66, and so on. Note that the mapping of the characters to these codes could be different for another system. You should never rely on these integer codes to identify the characters.
So when I try to print this value as integer (using %d as the format specifier), well what gets printed is the integer value of '1' which is 49. However, if we print this value as a character (using %c as the format specifier), what gets printed is the character whose integer code is 49. In other words, 1 gets printed.
Now try this code.
#include <stdio.h>
int main()
{
char s[] = "ABC123";
int i;
printf("char %%d %%c\n");
printf("---- -- --\n");
for (i = 0; i < 6; i++) {
printf("s[%d] %d %c\n", i, s[i], s[i]);
}
return 0;
}
Now you should see this output.
char %d %c
---- -- --
s[0] 65 A
s[1] 66 B
s[2] 67 C
s[3] 49 1
s[4] 50 2
s[5] 51 3
Does it make sense now? You need to use the %c format specifier when you want to print the character. You should use %d only when you want to see the integer code that represents that character.
Finally, let us come back to your code. This is how you fix it.
#include <stdio.h>
int main()
{
char number[10];
scanf("%9[^\n]", number);
printf("%c\n", number[0]);
printf("%c\n", number[1]);
return 0;
}
There are two things to note.
I have used %c as the format specifier to print the character representation of the digits read.
I have altered the format specifier for scanf to accept at most 9 characters only where the characters are not newline characters. This is to make sure that a user cannot crash your program by inputting a string that is far longer than 9 characters. Why 9 instead of 10?. Because we need to leave one cell of the array empty for the null-terminator. A longer input would overwrite memory locations beyond the allocated 10 bytes for the number array. Such buffer overruns lead to code that invoke undefined behaviour which could either cause a crash or kill your cat.
printf("%c\n",number[0]); //print the 1st digit in the number
printf("%c\n",number[1]);
should do the job for you, what you see are ascii values.
your number array is an array of char, and so every element of it is a char.
when you type:
printf("%d\n",number[0]);
you printing the chars as integers, and so you get the ASCII code for each char.
change your statement to printf("%c\n",number[0]); to print chars as chars not as ints
Warning! Your code invokes undefined behaviour!
char number[10]; // Can only store 9 digits and nul character
scanf("%s",number); // Inputting 1234567890 (11 chars) will overflow the array!
Use fgets instead:
#define MAX_LEN 10
char number[MAX_LEN];
if(fgets(number, MAX_LEN, stdin)) {
// all went ok
}
Once you have fixed this, you can fix the printing problem. You are printing the character code (number), and not the actual character. Use different type specifier:
printf("%c\n",number[0]);
I am fairly new to c programming, and also this forum but I thought I would give it a try. What I want to do is have a user enter a 4 digit number. From there i want to take the number and store it in an array, so as i could call arr[2] when I need it and so on and so on. Thanks in advance for any help!
I would really like to know what is going on here. Thanks again
Many possibilities exist to implementing the behavior you want. Here's one way of doing it:
int arr[4];
int i;
char var1[4];
printf("Please enter a 4 digit number: ");
scanf("%s", var1);
for (i = 0; i < 4; i++ ) {
arr [i] = var1[i] - '0'; // convert char to int
printf("%d", arr[i]);
}
printf("\n");
Your code does not do what you think it does. scanf reads a line from the console. %d matches a number (i.e. 123), not a digit (i.e. 1, 2, 3). You call printf in a loop, not scanf (i.e. you capture one number and you print it multiple times).
Actually, I see it is more than that - you are assuming integer in C++ means digit. Your array of 4 integers does not hold a 4 digit number - it holds four separate integers, each of which can be (usually) from -2147483648 to +2147483648.
The thing is, it's not easy to break a number into digits - because "digits" are base 10 (decimal) while a computer thinks in base 2 (binary). What we can do instead is read and write the number and digits as text, instead. Read the integer as a string, and write each digit as a character:
#include <stdio.h>
int main()
{
char input[4];
//get input as text, instead of as a number
printf ("Please enter a 4 digit number: ");
scanf ("%s", input);
for ( int i = 0; i < 4; i++ )
{
//print as char instead of as number
printf ("%c\n", input[i]);
}
}
This code is not perfect. If the user entered "blah" it will print "b" "l" "a" "h" instead of complain about non-numeric input. If the user enters more than 4 characters, our array of characters to hold the number will overflow causing serious security risks and a crash.
var1 is an integer and you are storing it in each element of the integer array arr, hence the output
If you want to store each number as a character, use fgets, or if you want to store it a number, do
i=0;
while(var1){
arr[len-i-1] = var1%10; //len is 4 in your case
var1 /= 10;
i--;
}
You have asked scanf to read an integer value. You might want to read a string instead.
In a pinch, you can use fgets:
char number[5];
if( fgets(number, sizeof(number), stdin) != NULL )
{
for( i = 0; i < 4; i++ ) {
printf( "%c\n", number[i] );
}
}