简体   繁体   English

从文件中读取错误的输入

[英]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. 前两个字符将确定其他内容,我需要读取一行,以便可以在一个数组中写入0 1 4并在另一个数组中写入0 2 4。

#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. 当我调试并遵循buffer [x]的值时,我发现当x = 0时,它始终具有值“ 10 \\ n”,而当x = 1时,其值始终为“ 0 \\ 0”。 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. 我还需要一行中的数据数量,因此仅使用fgets或getline是不够的。

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. 即使可行,将C中基于FILE *的I / O与C ++混合通常也是一个坏主意,这看起来很丑陋,并且开发人员似乎不知道自己在做什么。 You either do straight C99 or you do straight C++11 but not both. 您可以直接使用C99,也可以直接使用C ++ 11,但不能两者都使用。

This is the answer for C++: 这是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: 这是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
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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