for(i=0;i<t;++i)
{
scanf("%d",&arr[i]);
scanf("%d",&brr[i]);
a=arr[i];
b=brr[i];
}
This code block is taking inputs in two separate line(after pressing enter),ex
12
45
How to modify it so that it take both the numbers in a single line(after pressing space),ex
12 45
How to modify it so that it take both the numbers in a single
line(after pressing space)
Your code already does this (it already works if you pass "12 45" - you can put any amount of whitespace between them). If you want to you can use a single scanf call with something like:
scanf("%d %d", &arr[i], &brr[i]);
When using scanf it is a wise decision to check the return code, i.e. the number of scanned elements.
rc = scanf(...);
if (rc != 2)
/* We scanned less than we expected! */
Related
I wrote the below C code to check if a number is present in an array whose elements are input by the user. But weirdly it's skipping the the third printf statement, directly taking the input and printing Enter the number you wish to look for after taking that input. What is causing this? Included input and output box below code.
CODE:
#include <stdio.h>
#include <stdlib.h>
void main() {
int arr[30], size, i, num, flag=0;
printf("Enter size of array. \n");
scanf("%d",&size);
printf("Enter %d array elements one by one. \n",size);
for (i=0; i<size; i++) {
scanf("%d \n",&arr[i]);
}
printf("Enter the number you wish to look for. \n");
scanf("%d",&num);
for(i=0;i<size;i++) {
if (num == arr[i]) {
flag++;
}
}
if (flag>0) {
printf("The number %d is present in the array.",num);
} else {
printf("The number %d is not present in the array.",num);
}
}
INPUT/OUTPUT:
Enter size of array.
5
Enter 5 array elements one by one.
1
2
3
4
5
5
Enter the number you wish to look for.
The number 5 is present in the array.
You can see that Enter the number you wish to look for. should come before 5, but it is not so.
Solved
Simply fixed by removing \n from scanf.
In scanf, a space character already represents any whitespace. So in your "%d \n" the function already processes the new line right after the last digit, but then you force it to wait for another newline.
This causes the program to wait for yet another line. After it's input, the program continues and asks for the number to search, and at that point the input was already entered.
Just use only one space in scanf, it will already work for the newline, ideally before the digit itself so that you don't need one extra line to complete the operation:
scanf(" %d", arr + i);
The space in the input format string "%d \n" tells the input system to
consume... all available consecutive whitespace characters from the input
(described here)
So when you enter your last number 5, the system now tries to consume all whitespace characters. To do that, it waits for additional input, until it's not a whitespace. So, paradoxically or not, to consume spaces, the system has to read a non-space, which is the second 5 you input.
To fix this behavior, you can tell your system to input only a number, without consuming whitespace:
scanf("%d",&arr[i]);
However, this will leave the whitespace in the buffer, which may interfere with later input. To discard the whitespace, you can use various techniques, described e.g. here.
In my opinion, the most correct technique (however, maybe the most cryptic one) is
scanf("%d%*[^\n]%*c",&arr[i]);
%d - read the number
%*[^\n] - read a string, terminated by a newline byte; discard it and don't store it anywhere
%*c - read a byte (which is a newline byte); discard it and don't store it anywhere
BTW in your format string "%d \n", there are two whitespaces: a regular space and an end-of-line. They both tell scanf to consume all whitespaces in input. The effect is exactly the same as with one space "%d " or with one end-of-line "%d\n", so this particular format string may be highly confusing to whoever reads your code (including yourself).
I am getting comfortable with the foundations of C:-
There are two iterations of scanf() in this program. The first is fully functional.
The second appearance does nothing and instead quits the program and returns to the standard command prompt line.
Also, my second for loop only prints the first 4 numbers instead of 5.
Here is the code :
int main() {
int i;
int iNum[4]
int iMenu = 0;
printf("\n\n\tPlease enter five numbers: ");
for (i = 0; i < 4; i++) {
scanf("%d ", &iNum[i]);
}
printf("\n\tThank you. Here are your numbers: \n\t");
for (i = 0; i < 4; i++) {
printf("%d", iNum[i]);
}
printf("\n\tMenu:");
printf("\n1\tSort your numbers ascending.");
printf("\n2\tSort your numbers descending.");
printf("\n3\tQuit program");
printf("\n\nWhat would you like to do?\n\tEnter your option here: ");
scanf(" %d", &iMenu);
switch (iMenu) {
case 1:
printf("\nCase1testPrint");
sortAsc();
break;
case 2:
printf("\nCase2testPrint");
sortDesc();
break;
. . .//rest of code }
As soon as the program reaches the second scanf(), the program ends and returns to command prompt.
This is baffling, and I have tried many variations on what could be wrong. Please provide what you may.
Here is what it looks like if I run the program. Notice my entry "1" appears in the command line instead of the program:
C:\Users\Cortland\Documents\C projects>gcc arraysort.c
C:\Users\Cortland\Documents\C projects>a
Please enter five numbers: 3
6
5
4
5
Thank you. Here are your numbers:
3 6 5 4
Menu:
1 Sort your numbers ascending.
2 Sort your numbers descending.
3 Quit program
What would you like to do?
Enter your option here:
C:\Users\Cortland\Documents\C projects>1
Your for loop reads four numbers, not five.
You enter five numbers. The first four are read in the for loop. The fifth is read by
scanf(" %d", &iMenu);
So you've entered 3 6 5 4 as the four numbers, and then 5 as the choice of what to do. You haven't shown us the entire switch statement, but my guess is that it doesn't handle the value 5, and that it falls through and your program terminates.
(Also, you should always check the value returned by scanf(), and take some action if it indicates that the input operation failed.)
There are a couple of errors.
First off, the second line of your main() function contains a syntax error - there should be a semicolon at the end. This should stop your program from even compiling.
Second, even though you say you want the user to enter 5 numbers, your array and loops all use the number 4. The reason your program still allows you to enter five numbers, however, is because of how you've written the formatting string in your calls to scanf(). Instead of:
scanf("%d ", &iNum[i]);
use
scanf("%d", &iNum[i]);
Notice the lack of a space at the end of the formatting string? That's where your problems come in. Even though you are allowed to enter five numbers, the program only stores and checks four of them. The last number is stuck in the input stream - until, that is, your next call to scanf(). This fetches your last number, which is put through the switch/case statement (failing all cases, since you didn't input "1", "2" or "3"), and the program reaches the end of main() and exits. The "1" in the command line comes from trying to input something when the program has already ended.
Summarized:
1: Add the missing semicolon
2: Change the number used in the declaration of iNum and in the for loops from 4 to 5
3: Edit your scanf() calls, removing whitespace from the formatting strings.
This fixed the problem on my end.
I’m brand new to programming. I ‘m working on a homework assignment in order to help us understand scanf and arrays. The program is supposed to ask the user to input an unknown set of numbers. Each set of numbers should be separated by a space like below without hitting enter.
14 15 16
The user can also input numbers on a separate line instead using spaces, but again on the last number inputed the user isn’t supposed to hit enter.
12 13
44 55
5
The user should hit ctrl-d to indicate end of input. The program should display the number of elements entered by the user, along with displaying the numbers the user entered. I have been reading around and think I have a basic concept of how scanf works, but I am still having some difficulty. The code kind of works. However, if the user just enters the numbers on one line they need to hit ctrl-d three times in order for it to exit the loop and display the information.
From what I have found online and understand, I think it’s not working because the user hasn’t hit return, so the input hasn’t been flushed into the stdin. So if I'm understanding correctly, the first time I hit ctrl-d it while flush the input. Then the second time I hit ctrl-d it will finally put the EOF into the stream and the third time it will finally read the -1 produced by the EOF and exit the loop.
Is there anyway to force the input stream once ctrl-d is entered.
#include <stdio.h>
int main()
{
int numbers[20];
int i = 0, count, result, n;
int flag = 0;
printf("Please enter a seiries of numbers:\n");
while (flag == 0)
{
result = scanf("%d", &n); //scan user input into n variable along with getting scanf return value and storing in result variable
printf("result =%i \n", result); //Just printing scanf return value to insure it doing what I think it should be doing
if (result == 1)
{
numbers[i] = n; //if scanf return value is 1 places value of n into first element of array
i++; //used to increment my array
flag = 0;//keeps value of flag equal to 0 in order to stay in loop
}
if(result == -1) //checks to see if result = to -1 should be value returned if cntl +d is entered
{
flag = 1; //sets flag to 1 when cntrl +d is entered in order to exit loop.
}
}
for (count = 0 ; count < i ; count++) //loop to print I which is representing number of user inputs and the actual numbers entered by the user.
{
printf("\ni= %i numbers= %i\n", i, numbers[count]);
}
return 0;
}
I won't give you a solution directly, but will try to help you improve coding in C. The more you work with C the more you will find out that one can write pretty compact code, once the language is mastered.
You can omit flag because it depends on result.
And you could omit result because it is just the return value of scanf.
You can omit n and use numbers array directly.
And you could make use of the preprocessor to use a constant number (often for array sizes as in your case).
Have a look at this. Maybe it helps you get an idea:
#include <stdio.h>
#define COUNT 20
main() {
int numbers[COUNT];
int i;
i = 0;
while (scanf("%d", &numbers[i]) == 1 && i < COUNT)
printf("\t%d\n", numbers[i++]);
return 0;
}
P.S.:
I recommend getting acquainted with the different ways of accessing an array and reading about pointers. The have a very close relationship really.
Address of first element in array : numbers
Access ith element of array : numbers[i]
Equivalently : *(numbers + i)
Another equivalence : *(i+numbers)
Surprise, but equivalent again : i[numbers]
Address of ith element of array : &numbers[i]
K&R is a great resource of information and learning.
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 having a problem with this function (part of a Battleship game) where it will run through it once perfectly fine, but in subsequent executions, it skips:
scanf("%c",&rChar);
For some reason, rChar turns into another value without user input from above code.
I have tried putting in printf statements showing the value of rChar all throughout the function.
The function Conv_rChar_Int() converts the Char the user inputs into an integer value. But because rChar isn't being passed around as a pointer, the value of rChar remains the same throughout until the user replaces it on the next iteration. (Verified yet again with printf). The weird thing is, it changes right in between these lines of code. and never prompts the user for rChar.
printf("please enter the row you want to place your %d ship in\n",length);
scanf("%c",&rChar);
Remember, it only happens AFTER the first time. Even if I reinitialize the variables rChar, r, c, and dir after every iteration, this problem still happens.
I am 99% certain the problem is within this function and not in any of the functions that gets called within it (because rChar remains the same after every single line except between the 2 lines above).
Thanks for help in advance. If you have any questions about the code I'll try to explain it more.
int Gen_Ship_Place(int length, int flag3, int PlayGrid[10][10]){
int ShipPlaceFlag = 0;
//coordinates and direction
int r;
char rChar;
int c;
int dir;
//this loops until a ship location is found
while(ShipPlaceFlag == 0)
{
//enters row
printf("please enter the row you want to place your %d ship in\n",length);
scanf("%c",&rChar);
r = Conv_rChar_Int(rChar);
//adjusts row
r--;
//enter column
printf("please enter the column you want to place your %d ship in\n",length);
scanf("%d",&c);
//adjust column
c--;
//enter direction
printf("please enter the direction you want your %d ship to go\nwith\n0 being north\n1 being east\n2 being south\n3 being west\n",length);
scanf("%d",&dir);
//checks ship placement
ShipPlaceFlag = Check_Ship_Place(length,dir,flag3,r,c,PlayGrid);
//tells player if the location is wrong or not
if(ShipPlaceFlag == 0)
{
printf("****the location and direction you have chosen is invalid please choose different coordinates, here is your current board*****\n\n");
}
else
{
printf("****great job, here is your current board*****\n\n");
}
//prints grid so player can check it for their next move
Print_Play_Grid(PlayGrid);
}
Your program prints this prompt:
please enter the row you want to place your 2 ship in
and calls scanf. You type 5 and press return. You have typed in two characters: the 5 and a newline character \n. (Or maybe it's \r on Windows.) That newline character sits in the input buffer until the next call to scanf, which reads the newline character and returns right away without you needing to enter more input.
You can make scanf skip past newlines (and other whitespace) when reading a single character by putting a space before the %c specifier, like this:
scanf(" %c", &c);
When the user presses enter, that is also a character which will be in the input buffer. You'll need to read past that.
//prints grid so player can check it for their next move
Print_Play_Grid(PlayGrid);
while (fgetc(stdin)!='\n') { }