c: reading negative numbers with scanf() - c

I'm trying to read a list of input integers with scanf() separated by spaces into an array, but it breaks every time there's a negative number passed. How do I get it to read negative numbers as well?
for (int i = 0; scanf("%u", &val)==1; i++)
stdin:
1 2 -4 5
It will only put 1 and 2 into the array and then stop reading the rest of the numbers (I think because of the '-'?). How would I fix this?

Use the %d specifier instead of %u, %u expects unsigned values only.

Related

Input of multiple integers at once for dynamic array in C

My input consists of a sequence of integers, that need to be saved in a dynamic array. The number of integers is the first integer of the sequence. For example: 3 23 7 -12 or 5 -777 3 56 14 7
The sequence is ONE input.
How can i scan such an input?
For scanf("%i %i %i ...",)i need to know the amount of integers in advance, which i dont.
Use multiple scanf calls. First read the count, then read the values in a loop.
int count;
scanf("%i", &count);
int values[count];
for (int i=0; i<count; i++) {
scanf("%i", &values[i]);
}
Note that this doesn't include error checking for invalid values.
You can do it with a do-while loop:
int status = 0;
do {
status = scanf("%d", &placeToStoreVariablesAt);
} while(status);
Note that scanf() returns number of elements of correct type entered. If a char is entered, status becomes 0 and therefore program exits loop.

Why does my program return the first inputted value without the decimal every run?

#include <stdio.h>
int main (void) {
int count, value;
double avg, sum;
count = 0;
sum = 0;
printf("please input how many integers you have \n");
scanf("%d", &count);
for (int i = 0; i < count; i++) {
printf("please input your values \n");
scanf("%d", &value);
sum = sum + value;
}
avg = sum / count;
printf("your average is " "%f", avg);
}
Example: count input is 4. input values is 7.6, 1, 2, 3.
I understand that in the for loop scanf sees 7.6 first, but disregards the decimal point as it is not a valid form of input, and passes it along every subsequent scanf in the loop though they never truly accept an input. This results in the only inputted value as 7, but then the program should continue to divide 7 by 4 to retrieve the "Expected" average, but that is not the case. I end up with 7.000000, which I can't figure out why is happening.
Disregard the fact that I am prompting the user to input integer values even though floating point values were inputted because it is part of my homework assignment. Any hints or references to what I should study would be great
I understand that in the for loop scanf sees 7.6 first, but disregards the decimal point [..]
No. That's a matching failure as the input you enter (7.6) doesn't match the format specifier %d. Hence, scanf() fails. That's why you should always check the return code of all the standard functions. See 7.21.6.2 The fscanf function.
If you want to be able to read floating point values then you should read (change your code) to read floats (or doubles).
For example to read a double:
double value;
if (scanf("%lfd", &value) != 1) {
/* handle failure */
}
A general suggestion: Don't use scanf() if at all possible. Please read Why does everyone say not to use scanf? What should I use instead? for further explanation.
Your reasoning seems to be correct, except for the assumption that scanf will set value to zero on the subsequent iterations. Instead, after reading up to the period on the first iteration and assigning 7 to value, on subsequent iterations scanf will see the period, conclude that the input doesn't match the format, and not touch value at all, leaving it as 7 on every iteration. (It should return 1 on the first iteration and 0 on subsequent ones, to indicate the number of items matched and assigned)
So, the loop will add 7 on every iteration, and then divide by the number of iterations, giving a result of 7.

How can I read a varying amount of integer input in C?

I will be getting three lines of input. The first line will give me 2 integers and the third line will give me 1 integer. But the second line can give me any number of integers ranging between 1 to 100. For example, the input could be:
2 1
5 6 1 9 2
10
or could be:
10 4
5 6
9
I can read the second line of integer input into an integer array for a fixed number of integers, but cannot do so for a varying number of integers. I suppose, in this case, I should use a while loop which will break when scanf() finds a newline. How do I code that?
Read the line into a buffer (#John Coleman) using using fgets() or getline().
Parse the string looking for whitespace that may contain a '\n', exit loop if found. Then call strtol() or sscanf() to read the 1 number. Check that function's return value for errors too.
Repeat above steps.
I am actually a newbie in programming and am unaware of most of the functions. The only string functions I know of are strlen() and strcmp(). And my i\o function knowledge is limited to printf() and scanf().
Anyhow, I solved my problem in this way:
int a[101];
int i, num;
char ch;
for (i = 0; i < 101; i++)
a[i] = 0;
while (1)
{
scanf("%d%c", &num, &ch);
i = num;
a[i] = num;
if (ch == '\n')
break;
}
This works!
The value of num had to be equal to the value i because my program needed it.

Inputting Multiple values through Scanf - C

I am trying to solve an SPOJ problem. I am stuck here.
For the input, it asks me the following to take as input
Next line contain n elements, ai (1<=i<= n) separated by spaces.
I can use a loop and input each element given separately by the user through scanf. But as per the problem criteria, I am assuming that we need to take the input through scanf at once in a single line. Like scanf("%d %d %d", &a1 &a2 e.t.c).
But the range is like over 10^6, I am not sure how we can dynamically input multiple values through scanf in a single line.
You can run your iteration as you say, because scanf does not care what kind of whitespace separates integer inputs.
So: for (i = 0; i < n; ++i) scanf("%d", &array[i]); will work for inputs of the type:
3 2 1 2 3 8
as well as the type
3
2
1
2
3
8
Does not matter whether you input the numbers in a single line, this will work as scanf ignores the white spaces
int arr[1000001]; // Take an array to store the inputs
for(i=1;i<=n;i++)
{
scanf("%d",&arr[i]);
}

what is the %2d in scanf

I know the meaning of this statement
scanf("%d",&x);
But what does this statement do
scanf("%2d",&x);
I tried searching for this, but could not find an answer. I want to know what happens internally also.
That's two digits number:
int n = 0;
scanf ("%2d", &n);
printf ("-> %d\n", n);
12
-> 12
88657
-> 88
The number right after the '%' sign and right before the type of data you wish to read represents the maximum size of that specific type of data.
As you are reading an integer (%2d), it will only allow an integer up to two digits long. If you were to read a 50 characters long array, you should use %49s (leaving one for the null terminating byte). It is the same idea.
int number = 0;
scanf("%2d", &number);
printf("%d", number);
If the user passed 21 for the scanf() function, the number 21 would be stored in the variable number. If the user passed something longer than 21, i.e. 987, only the first 2 digits would be stored - 98.

Resources