From an input of n numbers(value of n is known) separated by spaces,
eg(here n is 6):
3 5 8 9 13 2
If I wish to accept only the 2nd and the 5th number and ignore the rest, how do I do it using scanf?
I found accepting the numbers in an array and using only the required ones a bit redundant, so I'm looking for a smarter alternative.
If the knwon number n is a fix number (n=6 always)
then you can use the following scanf
int a2, a5;
scanf("%*d %d %*d %*d %d %*d", &a2, &a5 );
scanf("%*d%d%*d%*d%d%*d", &firstNumber, &secondNumber);
Try this.
%*d reads the value, but ignores it in the name of good will.
Try this
int num,number1,number2;
for(int i = 0; i < 6; i++)
{
scanf("%d", &num);
if(i == 1)
number1 = num;
if(i == 4)
number2 = num;
}
I would read every number using scanf. Read not required ones in some temp variable and others in array or any variable (as required)
scanf("%*d %d %*d %*d %d %*d", &i, &j)
int v[6];
scanf( "%d %d %d %d %d %d", &v[0], &v[1], &v[2], &v[3], &v[4], &v[5] );
v[1] and v[4] contain the answers from your example.
Related
Sorry if my English is poor. What I'm trying to do is get the scanf to be entered on the same line. For example Enter value: 1 6 8 9 4 1 2 8 5 and it to be separated by a space. Then the numbers to be stored in an array. This is my code:
#include <stdio.h>
int main(void)
{
int a[10], smallest, i;
printf("Random\n");
for (i = 0; i < 9; i++)
scanf("%d", &a[i]);
smallest = a[0];
for (i = 0; i < 9; i++)
{
if (a[i] < smallest)
{
smallest = a[i];
}
}
printf("\nSmallest Element : %d\n", smallest);
}
Thanks for any help!
Edit: I'm trying to make the user enter 9 numbers which are stored in the array using scanf but when entering the numbers the scanf goes to a new line for example:
> 5
> 6 and so on what I want is for them to enter the number numbers on the same line with a space in between like this Enter value: 1 6 8 9 4 1 2 8 5
Scanf will await for a complete line. I suggest you take your input as a string then use strtok to extract the values and then assign.
Edit: You could use the scanf like that:
scanf( "%d %d ...", &a[0], &a[1]...); //as many values you're to assign
However, I prefer the method I proposed initially. Keep in mind scanf is derived from "scan formatted". You'll also have to handle the result from the scanf, it returns the number of values successfully filled.
you can scanf all numbers in one statement: scanf("%d %d %d %d %d %d %d %d %d %d", &a[0], &a[1], &a[2], &a[3], &a[4], &a[5], &a[6], &a[7], &a[8], &a[9]);
This will let you scan 10 numbers with spaces between them, without the need to hit enter every time
note that I scanned 10 ints, because your array can store 10 ints, while your loop only scans 9... (to fix it, change i < 9 to i < 10 as Sourav Ghosh suggested)
I want my code to prompt the user to input a phone number of form 1(xxx)-xxx-xxxx and then sum the digits of the number. However I do not know what is wrong with my code. See below
printf("Enter a phone number in 1(xxx)-xxx-xxxx format: \n");
scanf(" %*c%*c%d %d %d %*c%*c%d %d %d %*c%d %d %d %d", &i, &j, &k, &l, &m, &n, &o, &p, &q, &r);
sum = (i + j + k + l + m + n + o + p + q + r);
realsum = sum + 1;
printf("The sum of the digits = %d \n\n", realsum)
;
Can anyone help? It seems to be assigning the first part of the number (xxx) entirely to i, and j is zero. How do I get it to assign each digit to each variable one by one?
The problem is that %d keeps reading until it finds a character that can't be part of a decimal number. So if the user enters 1(123)-456-7890 then the first %d will set i to 123.
The solution is to use %1d. That tells scanf to read a one-digit decimal number.
btw: you should verify that the return value from scanf is correct. In this example, the correct return value is 10. Any other number indicates that the user did not enter a valid phone number.
You did account for the non-integer characters that the user enters, but integers are read as a whole, so 123 is not read as1 then 2 then 3 but rather as 123.
scanf(" %*c%*c%d %*c%*c%d %*c%d ", &i, &j, &k);
My console keeps on crashing after entering a few numbers. I am trying to get an array of 10 numbers from the user thru the console and then taking count of positives, negatives, evens, and odds. What am I doing wrong?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
int pos, neg, even, odd;
int nums[10];
printf("Give me 10 numbers: ");
pos = neg = even = odd = 0;
for(int i = 0; i < 10; i++){
scanf(" %d", nums[i]);
if(nums[i] > 0){
pos++;
if(nums[i] % 2 == 0){
even++;
}
else{
odd++;
}
}
else{
neg++;
}
}
printf("Positives: %d, Negatives: %d, Evens: %d, Odds: %d\n", pos, neg, even, odd);
return 0;
}
In your code,
scanf(" %d", nums[i]);
should be
scanf(" %d", &(nums[i]));
or,
scanf(" %d", nums+i);
as you need to pass the pointer to variable as the format specifier's argument in scanf() .
To elaborate, %d expects a pointer to int and what you're supplying is an int variable. it invokes undefined behavior.
That said,
Always check the return value of scanf() to ensure proper scanning.
int main() should be int main(void) to conform to the standard.
Modify scanf like scanf(" %d", &nums[i]);
scanf(" %d", nums[i]);
Scanf expects a pointer to a location to write to, and you're not giving it one.
Change your scanf to:
scanf(" %d", &(nums[i]));
to make your program work.
With this change I tested your program with stdin of
20 10 9 1 39 1 2 2 31 1
And recieved output:
Give me 10 numbers: Positives: 10, Negatives: 0, Evens: 4, Odds: 6
ideone of the thing for your testing purposes.
Change scanf(" %d", nums[i]); to scanf(" %d", &nums[i]);, because scanf() needs addresses. The parentheses around nums[i] isn't necessary, and may effect readability.
Also note that 0 is even, but not negative.
When scanf is usedto convert numbers, it expects a pointer to the corresponding type as argument, in your case int *:
scanf(" %d", &nums[i]);
This should get rid of your crash. scanf has a return value, namely the number of conversions made or the special value EOF to indicate the end of input. Please check it, otherwise you can't be sure that you have read a valid number.
When you look at your code, you'll notice that you don't need an array. Afterreading the number, you don't do aything with the array. You just keep a tally of odd, even and so on numbers. That means you just need a single integer to store the current number. That also extends your program nicely to inputs of any length.
Here's a variant that reads numbers until the end of input is reached (by pressing Ctrl-D or Ctrl-Z) or until a non-number is entered, e.g. "stop":
#include <stdlib.h>
#include <stdio.h>
int main()
{
int count = 0;
int pos = 0;
int neg = 0;
int even = 0;
int odd = 0;
int num;
while (scanf("%d", &num) == 1) {
count++;
if (num > 0) pos++;
if (num < 0) neg++;
if (num % 2 == 0) even++;
if (num % 2 != 0) odd++;
}
printf("%d numbers, of which:\n", count);
printf(" %d positive\n", pos);
printf(" %d negative\n", neg);
printf(" %d even\n", even);
printf(" %d odd\n", odd);
return 0;
}
Change scanf statement after for loop to
scanf(" %d", &nums[i]);
Whenever i try to read input with
for (int i = 1; i <= 10; ++i) {
scanf("(%c, %d, %d, %d)",&charv,&intv1,&intv2,&intv3);
}
I only get to scanf() once. What is the problem ?
Input -> (P, 1, 2, 3)......(P, 2, 3, 12)
Your usage of scanf() is wrong. You have to provide the pointer to the variable to store the value read by scanf(). You need to use it like below
for (int i = 1; i <= 10; ++i) {
scanf("%c, %d, %d, %d",&charVar,&intvar1,&intVar2,&intVar3);
}
EDIT:
Point 1: The supplied format string should exactly match with the input. Otherwise, scanf() will fail. If your input is not of format (<char>, <int>.... , it will fail. Either of missing (, ), , will cause mismatch in the supplied format string with the input and make scanf() to stop scanning. It's strongly recommended to check the return value of scanf() to ensure it's success.
Point 2: To avoid reading the \n stored by previous ENTER<\kbd> key press, you should add a leading space before %c. So, you can use something like
scanf(" %c, %d, %d, %d",&charVar,&intvar1,&intVar2,&intVar3);
^
|
Notice here
scanf("(%c, %d, %d, %d)",&charvar,&intvar1,&intvar2,&intvar3);
should be
scanf(" %c, %d, %d, %d",&charvar,&intvar1,&intvar2,&intvar3);
Note the space before %c which ignores newline if it exists. If your input is not separated by commas
scanf(" %c %d %d %d",&charvar,&intvar1,&intvar2,&intvar3);
Like Sourav Ghosh and Gopi said, scanf will not work properly with this syntax
scanf("(%c, %d, %d, %d)",&char,&int,&int,&int);
It should be
scanf("%c %d %d %d",&char,&int,&int,&int);
But you can read a string first, and then use sscanf.
Try this code:
char ch;
int a, b, c, i;
char teste[256];
for(i=0;i<10;i++){
fgets(teste, 256, stdin);
sscanf(teste, "(%c, %d, %d, %d)", &ch, &a, &b, &c);
printf("%c %d %d %d\n", ch, a, b, c);
}
I'm trying to read from a text file and store it into an array, but my last array is filled with garbage, is there any way to fix it? For reference, I don't need that last line of values, but I can't seem to find a way to get rid of it.
int k;
char string[100];
for(k = 0; k < MAX_STATIONS; k++){
if (fgets(string, sizeof(string), fp) == 0){
break;
}
fscanf(fp,"%d %f %d %d %d %d %d %f %f", &stationInfo[k].stationID, &stationInfo[k].temperature, &stationInfo[k].year, &stationInfo[k].month, &stationInfo[k].day, &stationInfo[k].hour, &stationInfo[k].minute, &stationInfo[k].location.latitude, &stationInfo[k].location.longitude);
printf("%d %1.2f %d %d %d %d %d %f %f\n", stationInfo[k].stationID, stationInfo[k].temperature, stationInfo[k].year, stationInfo[k].month, stationInfo[k].day, stationInfo[k].hour, stationInfo[k].minute, stationInfo[k].location.latitude, stationInfo[k].location.longitude);
}
EDIT: I've realized that using this method, I don't actually get the first line of my file read. How could I fix this?
You should check the return value of fscanf it returns the number of read fields and ignore (or print a warning) lines which are incomplete. Another idea would be to check whether 100 chars are really long enough to hold the longest line (+ EOS).