I recently started learning C and must create program that scanf two integer values from standard input separated by a space then printf the sum of these two integers. Must be able to accept negative values. I'm using repl.it to write code 1st then pasting in .c to compile.
Attempt:
#include <stdio.h>
int main(void) {
int j = 0;
printf("Enter 2 integers separated by space and press enter:\n");
while (scanf("%d", &j) == 1) {
printf("Here is the sum:"%d", j);
}
return 0;
}
Except this prints
Here is the sum: 1Here is the sum: 2
The output is wrong so what mistake did I make? Whats the correct method to get expected values?
(eg 1+2=3)
Your code is incorrect. It does not even compile due to "Here is the sum:"%d" ill formatted string. The program will repetitively scan an integer from standard input and print it as it was result of a sum.
Parsing two integers separated by a space can be easily done with scanf() function by using "%d %d" pattern. The function scanf() returns a number of successfully parsed arguments thus value of 2 is expected on correct input. Finally, add both number and print the result.
#include <stdio.h>
int main(void) {
int i, j;
if (scanf("%d %d", &i, &j) == 2) {
printf("Here is the sum: %d\n", i + j);
return 0;
}
Related
#include<stdio.h>
int main(void)
{
int h;
int m;
scanf_s("%d : %d", &h,&m);
printf("%d : %d", h,m);
return 0;
}
That is it,
I typed 12 13
It gave me 12 : -858993460
ironic.. would you give me an idea?
If you typed exactly "12 13" as you wrote in the question, then the issue is that your input does not match the format specified in your call to scanf. In particular, scanf is only looking for input in the form of <some integer> : <some integer>. Note that your input does NOT include the : character. As such, scanf only successfully reads a number into your first variable (h), but fails to read into the second variable (m).
You can confirm this is the case by checking the return value of scanf, which returns "the number of input items successfully matched" (see the man page).
The reason you're seeing a "random" number in the output is that your variable m is never initialized. If you instead initialize it to 0, then you will no longer see a "random" value. This is good practice anyway.
For example (with error check):
#include<stdio.h>
int main(void)
{
int h = 0;
int m = 0;
int rc = scanf_s("%d : %d", &h,&m);
if (rc != 2) { // expect to read 2 values
printf("scanf failed, read %d value(s)\n", rc);
} else {
printf("%d : %d", h,m);
}
return 0;
}
Keep the format in scanf_s("%d : %d", &h,&m);
scanf():
The C library function int scanf(const char *format, ...) reads formatted input from stdin.
In your case, type 12 : 13
Your call to the scanf_s function expects a colon in the input, but you didn't type one, so nothing got stored in m in the call. As a result, you got a garbage value for m (as you didn't initialize it either). If you type in 12 : 13, then you should get the expected result.
Also, make sure to check the return value of scanf_s to make sure that you've got all of the values you want.
So there is a problem on SPOJ as mentioned below:
Given two natural numbers (both not greater than 200), each number in the separate line, please print the sum of them.
Example Input:
2
3
Output: 5
So I wrote a program to this problem. Code:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int input1, input2, sum;
printf("Enter two natural numbers\n");
scanf("%d", &input1);
scanf("\n%d", &input2);
if ((input1>0&&input1<=200) && (input2>0&&input2<=200))
{
sum = input1 + input2;
printf("%d", sum);
}
return 0;
}
But SPOJ rejected this answer as a wrong answer.
Later I checked this on idone.
But I'm unable to detect, what's wrong with this answer, as expected it gives the same output given in above question.
Please correct if I'm wrong.
The first print statement
printf("enter two natural numbers\n");
The Second
scanf("%d",&input1);//Press Enter
The Third
scanf("%d",&input2);//Press Enter
And finally
printf("\n%d",sum);
First of all, remove the printf statement as it is not needed and will mess up the expected I/O as given by SPOJ.
Next, there is no need of the newline character in scanf. You can directly write scanf("%d %d", &input1, &input2);. Another way would be to write the scanf statement twice as:
scanf("%d", &input1);
scanf("%d", &input2);
Lastly, you can also remove the if statement, if input bounds are given by SPOJ.
So I'm trying to find the sum of an unknown amount of user-input numbers. Here's my code
int main()
{
int tmp1 = 1;
int tmp2 = 1;
int total = 0;
printf("Enter numbers for a sum: ");
tmp2 = scanf(" %d", &tmp1);
while(tmp2 > 0){
total+=tmp1;
tmp2 = scanf(" %d", &tmp1);
}
printf("total is %d", total);
return 0;
}
It gets stuck in an endless loop, and then once i hit ctrl-c to end it, it prints the correct sum. So what I'm doing wrong is how will i know when it's done scanning all the integers, and for the loop to end; since i'm not doing it correctly now
Decided to make it stop via ctrl d, and its acceptable. thanks
In your question, it is not clear how you expect your programme to understand that there won't be anymore numbers to input. Shall it be through a specific character? Or shall it just get a line of space-separated numbers and respond with a sum?
From your code, my most sensible guess is: You want it to understand that there won't be any more numbers to add, whenever it encounters a non-digital character. My guess is so, because this is almost exactly what your code does by checking the return value from scanf.
First of all, you have to change that tmp inside your loop into tmp1 because there isn't such a variable as tmp declared. edit: well, never mind
Then try running your programme, putting in any amount of white-space (space, tab or new-line) separated numbers, and then any non-digital character you like. May be a T for example, or ThoAppelsin, it won't matter. Programme won't get beyond the first character, in fact, not even beyond the first character. After that, you shall see that the numbers have been properly added together.
Since you're confused about a non-existent infinite-loop, my second guess is that you might be actually hoping it to get a single line of space-delimited numbers, and have the sum printed; and misinterpret your programme as "in infinite loop" while it merely expects further input from you, just like it does at the very beginning.
You won't get a 0 from non-redirected scanf("%d", &var);, unless you feed it with something that doesn't match to the format string to cause abnormal termination. If there's nothing left in the input stream to consume, it will just wait for more input. But say you give an 'a' to it, then all it can do is to give up and return zero, because it couldn't do a single assignment.
If you really are hoping to have a single line of numbers, then the minimal change I could offer would be something like this:
int main(void)
{
int tmp1 = 1;
char tmp2 = 0;
int total = 0;
printf("Enter numbers for a sum: ");
scanf("%d%c", &tmp1, &tmp2);
while(tmp2 == ' '){
total+=tmp1;
scanf("%d%c", &tmp1, &tmp2);
}
printf("total is %d", total);
return 0;
}
Of course, this approach has many vulnerabilities. However, if user is to input strictly a sequence like:
3 66 2 10 6
// mind the new-line
It will work fine. But if I'm allowed to change more than minimal, this is how I would do it:
#include <stdio.h>
#include <ctype.h>
#include <stdlib.h>
int main(void)
{
int LastNumber = 0;
int UpcomingCharacter = 0;
int Total = 0;
printf("Enter numbers for a sum: ");
while(scanf("%d%*[ \t]", &LastNumber) == 1)
{
Total += LastNumber;
UpcomingCharacter = getchar( );
if (!isdigit(UpcomingCharacter)) // eliminates a possible EOF return as well
break;
if (ungetch(UpcomingCharacter, stdin) != UpcomingCharacter)
{
fprintf(stderr, "%d: unexpected error with ungetch\n", __LINE__);
return EXIT_FAILURE;
}
}
printf("total is %d", Total);
return EXIT_SUCCESS;
}
Which should work fine on any whitespace-delimited sequence of numbers, excluding the new-lines of course.
For my C program, the user enters in "aY + b = c" where a, b, and c are int values and Y is a "symbolic constant."
How does one make it so that "aY+b=c" works as well as "aY + b = C" works? Basically, I am unsure of how to utilize scanf() so that I can grab my variables a,b, and c from the user input no matter how many spaces the user decides to input.
Thanks!
Consider the following:
Code
#include <stdio.h>
#include <ctype.h>
#define MAX_EQUATION_LEN (1000)
int main(void)
{
char equation[MAX_EQUATION_LEN];
int num, i;
printf("Enter a equation: ");
fgets(equation, MAX_EQUATION_LEN, stdin);
sscanf(equation, "%d", &num);
i = 0;
while(equation[i])
{
if(!isdigit(equation[i]))
break;
else
i++;
}
printf("You entered: %d\n", num);
printf("Unhandled string data: %s\n", &equation[i]);
return 0;
}
Example Run
Enter a equation: 204Y + 52 = 9
You entered: 204
Unhandled string data: Y + 52 = 9
Logic
Take the full equation in at one time as a string.
Parse the string accordingly. Here, I'm looking for the first int.
Keep track of where you are in the string parsing process.
Keep parsing the string until there are no more characters.
I am unsure of how to utilize scanf() so that I can grab my variables a,b, and c from the user input no matter how many spaces the user decides to input.
Don't use scanf in the first place. You need to write a lexer and a parser, so write a lexer and a parser.
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();
}