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.
Related
#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.
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.
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]);
}
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] );
}
}
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.