How to use scanf in for loop - c

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);
}

Related

I am having problem using scan function in C

Here if have used two format specifiers in scan function but it only proceeds after taking three numbers though only two numbers are stored.I don't know why is it waiting for the unnecessary 3rd number.
#include <stdio.h>
int main(){
int a ,b ;
printf("Enter values of a and b ");
scanf(" %d %d " , &a ,&b );
printf("a = %d b = %d" ,a ,b);
return 0;
}
why is it waiting for the unnecessary 3rd number.
" %d %d " directs scanf() to wait for some non-white-space after the 2 int to know all trailing white-spaces are consumed.
" %d %d" directs scanf() to return after the 2 int.
The initial space and the second one are actually redundant since %d reads and ignores whitespace before the number, so you can just write:
scanf("%d%d", &a, &b);
but you should also test that scanf() returns 2 indicating 2 successful conversions.
Here is a modified version:
#include <stdio.h>
int main() {
int a, b;
printf("Enter values of a and b: ");
if (scanf("%d%d", &a, &b) == 2) {
printf("a = %d, b = %d\n", a, b);
} else {
printf("invalid input\n");
}
return 0;
}
don't have this issue when I paste the code into this link https://c.runoob.com/compile/11

Why does this while-loop in C not work?

Ignoring the fact that negative numbers would not work here, why do positive integers create a infinite loop? I tried many combinations, as simple as a = 20 and b = 4, but every single one creates a infinite loop. What am I doing wrong or not seeing here?
#include <stdio.h>
int mdc(int a, int b) {
while (a != b) {
if (a > b)
a = a - b;
else b = b - a;
}
return a;
}
int main() {
int a, b;
printf("Valores mdc: \n");
scanf("%d %d\n", &a, &b);
printf("%d\n", mdc(a,b));
return 0;
}
Not an infinite loop for the given input:-
The thing is you have used \n in the scanf as a result unless you enter some non-whitespace character - it waits for it.
What did the '\n' do?
From standard explaining the why part - C11 N1570 §7.21.6.2¶5
A directive composed of white-space character(s) is executed by reading input up to the first non-white-space character (which remains unread), or until no more characters can be read. The directive never fails.
How to give input then?
So it will work if you do this:-
>>> 20 4 Enter
<Somenonwhitespace> Enter
Better solution:
Even better suggestion would be to use
scanf("%d%d", &a, &b);
You don't need to specify the space as you did - %d directive skips over the white space characters.
Code wise
if(scanf("%d%d", &a, &b)!=2){
fprintf(stderr,"Error in input\n");
exit(EXIT_FAILURE);
}
If you were to step the code in a debugger you would discover that the while loop is never even entered. It is not a problem of an infinite while-loop. Rather that scanf() never returns.
Change:
scanf("%d %d\n", &a, &b);
to
scanf("%d %d", &a, &b);
The line scanf("%d %d\n", &a, &b); should be scanf("%d %d", &a, &b); no \n.

How to read an unknown quantity of integers from console?

I have entries like these:
0 5 260
1 0 -598
1 5 1508
2 1 -1170
I don't know previously how many (console) inputs I'll get, so I have to read until there are no entries left.
I started with a code like this:
int a, b, c;
while(scanf("%d %d %d", &a, &b, &c)!=EOF){
// do stuff here
}
But it never stops asking for new input.
Then, I saw people in other threads suggesting this:
int a, b, c;
while(scanf("%d %d %d", &a, &b, &c)==1){
// do stuff here
}
In this case, it doesn't even enter the while.
Does anyone know what I'm doing wrong?
An approach: Continue asking for input until the input is closed (EOF) or some problem is encountered. (Invalid line of input)
The below uses fgets() to read a line.
Then, " %n" to detect where scanning stopped. If scanning does not reach %n, n will still have the value of 0. Otherwise it gets the offset in buffer where scanning stopped, hopefully it was at the null character '\0'.
char buffer[100];
while (fgets(buffer, sizeof buffer, stdin)) {
int n = 0;
sscanf(buffer, "%d%d%d %n", &a, &b, &c, &n);
if (n == 0) {
fprintf(stderr, "3 int were not entered\n");
break;
}
if (buffer[n] != 0) {
fprintf(stderr, "Extra input detected.\n");
break;
}
// do stuff here with a,b,c
}
There are many approaches to solve this issue.
while(scanf("%d %d %d", &a, &b, &c)==1)
means that "if scanf() successfully read just one value, proceed in the loop."
Therefore, if you enter something like 0 junk, the scanf() read just 1 data and will enter the loop once.
Try using
while(scanf("%d %d %d", &a, &b, &c)==3)
to have it enter the loop when scanf() successfully read three values, which is what expected.

selective input using scanf

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.

Converting a string of numbers into integers

I have a string (char) and I want to extract numbers out of it.
So I have string: 1 2 3 4 /0
And now I want some variables, so I can use them as integer: a=1, a=2, a=3, a=4
How can I do that?
The answers given so far are correct, as long as your string is formatted the way you expect. You should always check the return value of sscanf to make sure things worked okay. sscanf returns the number of conversions successfully performed, in the above case 4.
if (4 != sscanf(buf, "%d %d %d %d", &a, &b, &c, &d))
{
/* deal with error */
}
If buf was "1 2 3" or "1 2 a b" or something, sscanf would return a short item count.
As others have noted, if you know how many numbers to expect, sscanf is the easiest solution. Otherwise, the following sketches a more general solution:
First tokenize the string by spaces. The standard C method for this is strtok():
char* copy;
char* token;
copy = strdup(string); /* strtok modifies the string, so we need a copy */
token = strtok(copy, " ");
while(token!=NULL){
/* token now points to one number.
token = strtok(copy, " ");
}
Then convert the string to integers. atoi() will do that.
If the string always contains 4 numbers delimited with spaces, then it could be done with sscanf:
sscanf(string, "%d %d %d %d", &a, &b, &c, &d);
If the count of numbers varies, then you would need to parse the string.
Please clarify your question accordingly.
sscanf() can do that.
#include <stdio.h>
int main(void)
{
int a, b, c, d;
sscanf("1 2 3 4", "%d %d %d %d", &a, &b, &c, &d);
printf("%d,%d,%d,%d\n", a, b, c, d);
}

Resources