简体   繁体   中英

Reading wrong input from file

I am trying to write a program which should read a line and store its contents in an array, so it needs to read line by line and also read different characters in a line. For example my input is

4 6
0 1 4
0 2 4
2 3 5
3 4 5

First two characters will determine something else and I need to read a line so I can write 0 1 4 in an array and 0 2 4 in another array.

#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <list>
#include <iterator>

#define BUFFER_SIZE 50

int main()
{       
using namespace std;

int studentCount, courseCount;
FILE *iPtr;
iPtr = fopen("input.txt", "r");
if(iPtr == NULL){ printf("Input file cannot be opened!\n"); return 0; }

fseek(iPtr, 0, SEEK_SET);
fscanf(iPtr, "%d", &studentCount);
fscanf(iPtr, "%d", &courseCount);

list <int> S[studentCount]; // an array of linked lists which will store the courses
char buffer[BUFFER_SIZE];
char temp[BUFFER_SIZE];
int data;
int x=0, counter=0; // x traces the buffer

fgets(buffer, BUFFER_SIZE, iPtr);
while( buffer[x] != '\0')
{
   if( isspace(buffer[x]) ) counter++;
   x++;
}
printf("%d\n", counter);

fflush(stdin);
getchar();
fclose(iPtr);
return 0;
}

When I debug and follow the values of buffer[x] I see that it always have the value "10 \\n" when x=0 and then "0 \\0" when x=1. How can I fix this, or is there a better method for reading line by line? I also need the number of data in a line so using fgets or getline is not enough by itself.

Even if it works, it is an generally a bad idea to be mixing FILE* based I/O from C with C++, it looks ugly and the developer looks as if he or she doesn't know what he or she is doing. You either do straight C99 or you do straight C++11 but not both.

This is the answer for C++:

#include <fstream>
...
std::ifstream infile("thefile.txt");
int ha,hb;
infile >> ha >> hb;
// do whatever you need to do with the first two numbers
int a, b, c;
while (infile >> a >> b >> c)
{
    // process (a,b,c) read from file
}

This is the answer for C:

fp = fopen("thefile.txt","r");
// do whatever you need to do with the first two numbers
fscanf("%d %d",&ha,&hb);
int a, b, c;
while(fscanf(fp,"%d %d %d",&a,&b,&c)==3){
        // process (a,b,c) read from file
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM