How to take a space as input in scanf() ie in c? - c

I want to store a few numbers in an array. While giving the input though, I cannot use an enter to move from one position to the next. I need to use a space.
Eg:
input:2 3 4 5
instead of:
input: 2
3
4
5
Can someone please tell me the correct syntax?

You can do it like this
#include <stdio.h>
int main(void){
int a, b, c, d;
printf ("Enter 4 integers: ");
if (4 != scanf("%d%d%d%d", &a, &b, &c, &d))
printf ("Invalid input\n");
else
printf ("You entered %d %d %d %d\n", a, b, c, d);
return 0;
}
Program output:
Enter 4 integers: 2 3 4 5
You entered 2 3 4 5
Be aware though that if you only enter 3 integers you won't get the error message, because the program is still waiting for a fourth. You get the error if the inputs were not integers.
And note that you have to terminate the input with Enter key.

You can just go ahead with scanning an integer like
int a[5];
for(i=0;i<5;i++)
{
if(scanf("%d",&a[i]) != 1)
break;
}
%d will consider an integer input until an newline or a space is encountered.

Related

Using Scanf with pointers

I am fairly new to C and I am having trouble using scanf with pointers. I have been told to get user inputs for 3 int and 1 char values and then print them back out using pointers.
This is the best I could come up with so far:
int a, b, c;
char d;
int *x = &a;
int *y = &b;
int *z = &c;
char *e = &d;
scanf("Enter 3 Ints and 1 Char:%d %d %d %c", x, y, z, e);
printf("The numbers are:\n");
printf("%d\n %d\n %d\n %c\n", a, b, c, d);
return 0;
When I enter the values the following is printed out:
2 3 4 c
The numbers are:
32708
-613084440
32708
�
Again, I'm very new to programming so I apologize if this is a stupid mistake or something obvious that I have missed.
You are not checking the return value of your scanf, otherwise you would know that it returns 0, as in 'no elements read'.
Your scanf expects you to write exactly what you are putting in there, so, if you entered Enter 3 Ints and 1 Char:2 3 4 c, it would probably work.
What you want, however, is this:
printf("Enter 3 Ints and 1 Char: ");
if (scanf("%d %d %d %c", &a, &b, &c, &d) != 4)
printf("Invalid input detected\n");
else
printf("The numbers are:\n%d\n %d\n %d\n %c\n", a, b, c, d);
The first line will print the prompt to the console, the second will read the values into variables.
There is no need to create separate pointer variables for this purpose.

Detect two type of input in C

Assume that i have two types of query
one is 1 2 3
and the other one is 2 3
if the head (index 0) is 1, then the total number within the input are 3 (1 2 3)
and if the head is 2 then the total number within the input are 2 number (2 9)
How do I detect it? Thank you
The problem that I have is that I scan the 3 of them
scanf("%d %d %d",&a,&b&c)
so, when I only have total of 2 number in the input (2 3) The program wont continue
Thank you
You use the return value of scanf() to detect this, and you should generally always check return values. They are given for a purpose.
#include <stdio.h>
int main(void) {
int a;
int b;
int c;
printf("Please enter 2 or 3 numbers: ");
int n = scanf("%d%d%d", &a, &b, &c);
switch (n) {
case 2:
printf("You have entered 2 numbers, %d and %d\n", a, b);
break;
case 3:
printf("You have entered 3 numbers, %d, %d and %d\n", a, b, c);
break;
default:
printf("Well, you made an error.\n");
break;
}
}
Note 1: Even printf() returns a value, commonly the number of characters printed. In this simple example, we can ignore it.
Note 2: It is always a very good idea to read the documentation of functions you use, if you don't know them in detail.

How do you take input separated by space in a single line in C?

I was attempting the CodeChef contest today where I came across this problem. I managed to do the code, but there's one error that I don’t know how to take all inputs in a single line separated by space. I checked thousands of answers on Stack Overflow, but I still didn’t get it. How can I fix this problem?
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main()
{
int t, n, a, b, c, x, y, z;
//printf("No. of test cases\n");
scanf("%d", &t);
for(int i=0; i<t; i++)
{
//printf("Enter three inputs\n");
scanf("%d\t%d\t%d", &a, &b, &c);
}
x = a + b;
y = b + c;
z = a + c;
if(x>y && x>z)
{
printf("%d", x);
}
else if(y>a && y>z)
{
printf("%d", y);
}
else
{
printf("%d", z);
}
}
It is the same and is not a big deal.
Just enter your first input and instead of pressing Enter, you press Space. Then enter your second input, press Space again, enter the third input, and then press Enter. It will definitely work.
I will show you two programs and then may be you see a way to read the values in a controlled way.
scanf() is controlled by the mask, the thing like "%d\t%d\t%d" in your code. And scanf() has the notion of white space, treating spaces and tabs and newlines as same thing. These sometimes makes a mess when reading keyboard input, because scanf() refuses to end and keeps reading trying to satisfy the supplied input mask. [See the first example program].
Fact is that these functions were written to consume tabular data, like CSV files --- Hence the name: scan formatted input. But stdin with a keyboard with 105 keys are not formatted input: The user can key anything in.
Always test the return of scanf()
scanf() returns a negative value for error, or the number of items read. In your case, it can return 0, 1, 2 or 3: there are three fields to be read in "%d\t%d\t%d"
Example 1
#include <stdio.h>
int main(void)
{
int A, B, C;
int res;
do
{
printf("\n==> Enter up to 3 integer numbers, separated by spaces: ");
res = scanf("%d %d %d", &A, &B, &C);
switch (res)
{
case 0:
printf("\nscanf() read no numbers\n");
break;
case 1:
printf("scanf() read a single value, A = %d\n", A);
break;
case 2:
printf(
"scanf() read two values, A = %d, B = %d\n", A, B);
break;
case 3: // Fall-through
default:
printf(
"scanf() read all 3 values, A = %d, B = %d, C = "
"%d\n",
A, B, C);
break;
}; // switch()
} while ( res != 0);
return 0;
}
This code uses scanf() on stdin as usual.
Some results from example 1
==> Enter up to 3 integer numbers, separated by spaces: 1 2 3
scanf() read all 3 values, A = 1, B = 2, C = 3
All good when the numbers come as expected...
==> Enter up to 3 integer numbers, separated by spaces: 1 2
3
But now scanf() reads 1 and 2, but the user entered a few newlines, that scanf() skips like white space and will forever until read a letter or the final digit
And note this one:
==> Enter up to 3 integer numbers, separated by spaces: 1 end
scanf() read a single value, A = 1
==> Enter up to 3 integer numbers, separated by spaces:
scanf() read no numbers
The user entered 1 end. As soon as the e is read scanf() returns 1 and A is set to 1, of course. But then the next call has the end letters and the newline to read, so the next call of scanf() reads these letters, returns 0 and the program ends.
This is the kind of outcome that surprise many beginners and even a few professionals sometimes.
And these is hard to control.
For these reason many times is better to read the whole line by other means, and use sscanf() to consume the data, as in example 2. The idea is that all data in the line is consumed, and sscanf() parses the data from memory.
I believe that the example is ok to understand.
Example 2
#include <stdio.h>
int main(void)
{
int A, B, C;
int res;
printf("Enter up to 3 integer numbers, separated by spaces or ENTER to exit: ");
char line[100] = {0};
char* p = line;
// read whole line, up to the possible '\n'
p = fgets( line,100,stdin);
if ( p[0] == '\n') return 0; // input empty
do
{
res = sscanf(line, "%d %d %d", &A, &B, &C);
switch (res)
{
case 0:
printf("scanf() read no numbers\n");
break;
case 1:
printf("scanf() read a single value, A = %d\n", A);
break;
case 2:
printf(
"scanf() read two values, A = %d, B = %d\n", A, B);
break;
case 3: // fall thru
default:
printf(
"scanf() read all 3 values, A = %d, B = %d, C = "
"%d\n",
A, B, C);
break;
}; // switch()
printf("Enter up to 3 integer numbers, separated by spaces or ENTER to exit: ");
p = fgets( line,100,stdin); // next line
if ( p[0] == '\n') return 0; // input empty
} while ( res != 0 );
return 0;
}
Output for example 2
Enter up to 3 integer numbers, separated by spaces or ENTER to exit: 1
scanf() read a single value, A = 1
Enter up to 3 integer numbers, separated by spaces or ENTER to exit: 1 2
scanf() read two values, A = 1, B = 2
Enter up to 3 integer numbers, separated by spaces or ENTER to exit: 1 2 3
scanf() read all 3 values, A = 1, B = 2, C = 3
Enter up to 3 integer numbers, separated by spaces or ENTER to exit: 1 2 end
scanf() read two values, A = 1, B = 2
Enter up to 3 integer numbers, separated by spaces or ENTER to exit: end
scanf() read no numbers
Enter up to 3 integer numbers, separated by spaces or ENTER to exit:
And things are a bit easier to control.

scanf with variable arguments (C lang)

My Input is as below.
3 8 9 3
4 2 4 0 3
5 1 5 9 3 1
0
1 5
As you can see, the first number of each line means the number of how many inputs left in the line.
How can I get all input via scanf?
Or please let me know something new.
As mentioned in the comments, the problem with scanf() is (among other things) the way it handles the newline character. However, the sscanf() function (reading from a string) doesn't have this issue! So, depending on exactly what you're trying to achieve, maybe something like the following code will help:
#include <stdio.h>
int main()
{
int a[5], n = 0, given;
char buffer[200];
while (n >= 0) {
printf("\nEnter n and a list of numbers: ");
fgets(buffer, 200, stdin);
printf("Input was: %s", buffer);
n = -1;
given = sscanf(buffer, "%d %d %d %d %d %d", &n, &a[0], &a[1], &a[2], &a[3], &a[4]);
if ((given < 1) || (given != n + 1)) printf("Invalid input!\n");
}
return 0;
}
I'm not saying it's an ideal solution, or even that you could use it, but it may give you some clues as to where to go next.
Let me know how you find it.

Trying to make scanf not go to a new line in a for loop (C Programming)

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)

Resources