简体   繁体   English

C ++以2D数组读取文件

[英]C++ Read file in 2D array

I'm almost frustrated with this program. 我对此程序几乎感到沮丧。 I have a file that contains 100 records but, my output will not go beyond 17 including the header. 我有一个包含100条记录的文件,但是我的输出不会超过17(包括标题)。 Can anyone tell me what I am doing wrong? 谁能告诉我我在做什么错?

#include "stdafx.h"
#include <iostream>
#include <fstream>

using namespace std;

char medRecord[100][8];
int header, person;

int main()
{

    ifstream in("fakedata.txt");
    if(!in){
        cout << "Cannot open file. \n";
        return 1;
    }

in.read((char *) &medRecord, sizeof medRecord);

for(person = 0; person < 100; person++)
     for(header = 0; header < 8; header++)
cout << medRecord[person][header] << "";

return 0;

}

Output: 输出:

Number,Gender,GivenName,Surname,Birthday,BloodType,Pounds,FeetInches
1,male,Joseph,Doody,1/10/1968,A-,179.5,5' 7"
2,male,Robert,King,8/17/1985,A+,203.1,5' 10"
3,male,Richard,Murphy,3/18/1944,O+,235.6,6' 1"
4,female,Caroline,Acosta,5/27/1959,B+,145.4,5' 8"
5,male,John,Capps,12/18/1967,O+,186.6,5' 9"
6,female,Stephanie,Guidry,3/25/1981,O+,177.8,5' 6"
7,female,Janet,Kimmel,2/23/1977,A+,161.3,5' 7"
8,male,Jerrell,Wright,8/4/1929,B+,140.6,5' 9"
9,female,Cheryl,Johnson,12/8/1972,A+,128.7,5' 1"
10,female,Sandra,Gonzalez,6/1/1974,A+,171.4,5' 9"
11,male,Kevin,Noel,9/30/1939,O+,212.1,5' 6"
12,female,Krysta,Booth,7/9/1940,O+,173.1,5' 3"
13,male,Sam,Clark,7/5/1979,A+,162.4,5' 9"
14,male,James,Graves,8/15/1959,A+,235.0,5' 8"
15,male,Elton,Fink,6/30/1937,A+,198.4,5' 5"
16,male,Robert,Daniels,10/14/1969,Press any key to continue . . .

Your medRecord array contains 800 characters. 您的medRecord数组包含800个字符。 The outputted text contains 783 characters, one line short (or less) of 800. So, sight unseen, what you're probably doing is trying to read the entire file into medRecord , and the readin or outputting stops when it gets filled up. 输出的文本包含783个字符,一行短(或少于800行)。因此,看不见,您可能正在做的是尝试将整个文件读入medRecord ,并且读medRecord停止输出。

I counted by cutting/pasting into Open Office--if the newlines aren't getting counted properly, then 783 + 17 = 800 and there you go. 我是通过剪切/粘贴到Open Office来计算的-如果未正确计算换行符,则783 + 17 = 800,然后就可以了。

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

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