I have to read from a .txt like this (1. - txt line)
1 2
1 2 3
1 3 4
but I have to read like: "1" first line, attribute to x[0], "2" first line attribute to x[1]. I know how to do that but the problem is that I have to skip to the line 2 and do the same, but it doesn't work.
So It'd be like
x[2]=1. x[2]=2, x[3]=3, x[4]=1, x[5]=3, x[6]=4
Is there a way for me to do it???
Thanks!
Let me try to be more especific
1 2 1
2 3 1
3 4
Imagine this is a txt file where 3. 2. and 1. are first, second and third line. I have to read each number on each line and assign to a vet[MAX];
I can do it, but only with the first line. I don't know how to skip to the second one
My code
#include <stdlib.h>
int main (void)
{
char buf[1024];
int numeros[8];
FILE *fp = fopen("teste.txt", "r");
if(fp == NULL)
return EXIT_FAILURE;
while(fgets(buf, sizeof(buf), fp)) {
if(buf[0] == '\n')
continue;
sscanf(buf, "%d %d %d %d %d %d %d", &numeros[0], &numeros[1], &numeros[2], &numeros[3],&numeros[4], &numeros[5], &numeros[6]);
}
fclose(fp);
printf(" \n %d \n %d \n %d \n %d \n %d \n %d \n %d", numeros[0], numeros[1], numeros[2], numeros[3],numeros[4], numeros[5], numeros[6]);
}
the output
3
4
1
131072
2685712
302692880
4798692
Process returned 53 (0x35) execution time : 0.016 s
Press any key to continue.
And I wanted
1 2 2 1 2 3 1 3 4
Assuming your double use of x[2] is a typo, and assuming the line numbers are not really in the file, all you need is to loop doing:
fscanf(file, "%d", &x[i++]);
until it fails. So remember the check the return value, if it isn't 1 it failed to find a number to convert and store, and you should stop.
Of course, this assumes that x has space enough, and that i is initialized to 0.
Use the result of sscanf().
You will likely get 2 or 3 each loop. This means 2 or 3 int were successfully scanned. This number can then be used to determine saving the int in numeros[].
int i=0;
while(fgets(buf, sizeof(buf), fp)) {
int t[7];
int result = sscanf(buf, "%d %d %d %d %d %d %d", &t[0], &t[1], &t[2], &t[3], &t[4], &t[5], &t[6]);
if (result <= 0) break; // EOF, IO error, bad data
for (int r=0; r<result; r++) {
if (i >= sizeof(numeros)/sizeof(numeros[0[)) break; // too many
numeros[i++] = t[r];
}
}
Related
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.
This question already has answers here:
scanf() leaves the newline character in the buffer
(7 answers)
Closed 3 years ago.
For example, 1st input is "B 2 A 0" press Enter. team1[0] = 'B' and rest of it is addressing True. No problem so far.
But in 2nd input this happens.. assume that this is my 2nd input >> "A 1 B 1"
team1[1] is not 'A'. as you guessed score1[1] and score2[1] is not 1 either, and that's why im asking.
// the first versions of the arrays
// 0x7fffffffea60 "p\353\377\377\377\177" team1[size]
// 0x7fffffffea50 "\240\353\377\377\377\177" team2[size]
// after 1st input ( assume "B 2 A 0" )
// 0x7fffffffea60 "B\353\377\377\377\177" team1[size]
// 0x7fffffffea50 "A\353\377\377\377\177" team2[size]
// after 2nd input ( assume "A 1 B 1" )
// 0x7fffffffea60 "B\n\377\377\377\177" team1[size]
// 0x7fffffffea50 "A\353\377\377\377\177" team2[size]
char team1[size];
char team2[size];
int score1[size];
int score2[size];
for(i=0;i<size;i=i+1)
{
scanf("%c %d %c %d",&team[i],&score1[i],&team2[i],&score2[i]);
}
With
char team1[size];
char team2[size];
int score1[size];
int score2[size];
for(i=0;i<size;i=i+1)
{
scanf("%c %d %c %d",&team[i],&score1[i],&team2[i],&score2[i]);
}
And as you say
1st input is "B 2 A 0" press Enter.
the enter is not read by your first scanf and is still available, so the second loop the first %c gets it then scanf see A for the first %d and returns without setting score1[1] team2[1] and score2[1]
As said in a remark you can use " %c %d %c %d", that bypasses spaces and newlines at the beginning of the input.
Note you already uses that bypassing putting a space between %d and %c so N 2 A 0 is read as expected
As also said in a remark check the result of scanf valuing 4 when the inputs are ok
#include <stdio.h>
#define size 100
int main()
{
char team1[size];
char team2[size];
int score1[size];
int score2[size];
int i, j;
for(i=0; i < size; ++i)
{
if (scanf(" %c %d %c %d", &team1[i], &score1[i], &team2[i], &score2[i]) != 4)
break;
}
/* check */
puts("input values:");
for(j=0; j<i ; ++j)
{
printf("%c %d %c %d\n", team1[j], score1[j], team2[j], score2[j]);
}
}
Compilation and execution :
pi#raspberrypi:/tmp $ ./a.out
B 2 A 0
A 1 B 1
C 22 D13
input values:
B 2 A 0
A 1 B 1
C 22 D 13
(I used the non visible control+d to finish the input)
I have the following dataset:
0 1
0 3
1 1
2 3
<empty line>
My goal is to read these points into two integers, x, and y. Obiviously, I do not want to read in the blank line at the end of the file, so I wrote the following code to avoid that.
#include <stdio.h>
#include <math.h>
int main() {
FILE *input;
int x, y;
const float r = 2;
input = fopen("coords.dat", "r");
for (;;) {
int nread = fscanf(input, "%i %i\n", &x, &y);
if (!(nread >= 1)) break;
fscanf(input, "%i %i\n", &x, &y);
printf("%i %i\n", x, y);
}
fclose(input);
}
Essentially, if a line is blank, I break out of the loop. I know for a fact that my .dat file has a blank line at the end. However, I get the following output:
0 3
2 3
Evidently, this code is skipping every other line. Why is this happening?
You are doing the fscanf twice but printing only at the end. You should remove the second fscanf from the for loop
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.
I am writing a little program for reading a file formatted like that :
2 2
1.0 2.0
5.0 5.1
6.5 3.1
5.1 2.3
3 1
4 1 2 3 5 2
1 4 5 2 6 5
1 4 5 2 3 6
I am using fscanf to read the first two integers and allocate an array to store all four float that follows. It works fine. But when the "cursor" arrives to the line that contains integers "3 1", it stops working for any reason...
float *c = NULL;
float **coord = NULL;
f = fopen("mesh.dat", "r");
if( f != NULL ){
/* the first two integers */
fscanf(f, "%d %d", &n1, &n2);
n = n1*n2;
c = malloc(2*n*sizeof(float));
coord = malloc(2*sizeof(float *));
for(i=0; i<2; i++){ coord[i] = &c[i*n1]; }
/* reading all coordinates */
for(i=0; i<n; i++){ fscanf(f, "%f %f", &coord[0][i], &coord[1][i]); }
/* reading the two integers */
fscanf(f, "%d %d", &n, &t);
printf("n = %d, t = %d\n", n, t);
}
fclose(f);
The program stops here. Because it doesn't read the integers "3 1".
Any idea ?? I'm tearing out my hair trying to understand...
This line:
fscanf(f, "%d %d", &n1, n2);
Should be
fscanf(f, "%d %d", &n1, &n2);