代碼(粘貼在下面)應該讀取輸入文件,然後將數據解析到結構中的適當位置。用get.line跳過空行
如果正在讀取的文件沒有空格,則正確讀取數據。但是一旦數據有空行,文件就會陷入無限循環。
我一直在閱讀關於跳空行/空行。
我試着用"if (buffer[0] == '\n')"
然後再讀一行。但它根本不工作!
是否有人知道將允許的代碼(如果有多個空白行,我正在使用while循環。)我跳過空行並允許代碼解析所有數據。
的文件中讀取應該是這樣的
"
<student>
<first>
1FRED
</first>
<mi>
J
</mi>
<last>
JOHNSON
</last>
<ssn>
123456788
</ssn>
</student>
<STUDENT>
<FIRST>
2SUSIE
</FIRST>
<MI>
Q
</MI>
<LAST>
WATSON
</LAST>
<SSN>
234567899
</SSN>
</STUDENT>
"
下面的代碼:
#include <iostream>
#include <cstdlib>
#include <fstream>
#include <stdio.h>
#include <cstring>
#include <strings.h>
using namespace std;
struct record
{
char first [20];
char mi [1];
char last [20];
int ssn;
};
void filename (char ifname [], struct record *student[]);
void structfill (fstream & infile, struct record *student[]);
int main()
{
system ("clear");
fstream infile;
char ifname [256];
struct record * student [50];
filename (ifname, student);
return 0;
}
/*******************************************************************/
void filename (char ifname [],record *student [])
{
fstream infile;
cout << "Enter name of file to read from: ";
cin.getline (ifname, 256);
cout << endl;
infile.open (ifname);
if (!infile.is_open())
{
cerr << "FILELOOP!: Unable to open input file " << ifname
<< endl;
exit (1);
}
structfill (infile, student);
}
/*******************************************************************/
void structfill (fstream & infile, record *student [])
{
char buffer [81];
int buffernumber [81];
int n=0;
int f=0;
infile.getline (buffer,81);
while (!infile.eof())
{
if (strncasecmp (buffer, "<student>",9)==0)
{
student[n] = new record;
while ((strncasecmp (buffer, "</student>",10) != 0))
{
infile.getline (buffer, 81);
if (strncasecmp (buffer, "<first>",7)==0)
{
infile.getline (buffer, 81);
if (buffer[0] == '\n')
{
infile.getline (buffer, 81);
cout << "-----";
}
strcpy (student[n]->first, buffer);
}
if (strncasecmp (buffer, "<mi>",4)==0)
{
infile.getline (buffer,81);
if (buffer[0] == '\n')
infile.getline (buffer, 81);
strcpy (student[n]->mi, buffer);
}
if (strncasecmp (buffer, "<last>",4)==0)
{
infile.getline (buffer, 81);
if (buffer[0] == '\n')
infile.getline (buffer, 81);
strcpy (student[n]->last, buffer);
}
if (strncasecmp (buffer, "<ssn>",4)==0)
{
infile.getline (buffer, 81);
if (buffer[0] == '\n')
infile.getline (buffer, 81);
}
} n++;
infile.getline (buffer,81);
}
}
for (int a =0; a < n; a++){
cout << student[a]->first << " " << student[a]->mi << " " << student[a]->last << a << endl;
}
}
嘗試檢查字符串是否爲空,即'strlen(s)== 0' – user1520427
我試過了,它仍然會進入無限循環。 – user3304639