从输入文本文件读取不同长度的cstrings到链表

时间:2014-02-17 22:00:21

标签: c++ linked-list c-strings

我目前正在进行一项任务,要求我使用cstrings将输入文本文件中的名称和其他各种数据读入链接列表。我已经完成了所有必要的组件减去一件事。除了一个名字之外的所有名字都包含三个单词。输入文本文件的最后一行只包含两个单词,放弃了正确读取输入文本文件的循环。输入文本文件如下:

12345678901234567890123456789012345678901234567890

Bugs Bunny Jr. 1234 1001.01

博士。 Wiley Coyote 2345 1002.02

Taco Speedy Gonzales 3456 1003.03

Billy the Goat 4567 1004.04

Porky Pig 5678 1005.05

这是我的函数代码:

void inputfn(customerType *&head){
 customerType *currptr, *nnptr;
 head=NULL;
 fin.ignore(50,'\n');
while(fin){
   //create first node if head is null
   if(head==NULL){
                  head=new customerType;
                  fin>>head->name[0]>>head->name[1]>>head->name[2]>>head->pin>>head->balance;
                  currptr=head;
                  if(fin.peek()=='\n')fin.ignore();//in case there is only one record
                  }//end of first node 

    nnptr=new customerType;

    fin>>nnptr->name[0]>>nnptr->name[1]>>nnptr->name[2]>>nnptr->pin>>nnptr->balance;
    currptr->link=nnptr;//linked the nodes
    currptr=nnptr;//advanced currptr
    if(fin.peek()=='\n')fin.ignore();  
           }//end of while

//end of creating a linked list
 }//end of inputfn

由于它正在读取三个名称,因此将PIN作为姓氏而不是实际的PIN。这导致我的输出看起来像这样:

Bugs Bunny Jr. 1234 1001.01

博士。 Wiley Coyote 2345 1002.02

Taco Speedy Gonzales 3456 1003.03

Billy the Goat 4567 1004.04

Porky Pig 5678 1005 05

我知道必须有一个简单的方法解决这个问题,但由于我必须使用循环来读取数据,我在找到答案时遇到了问题。任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:1)

我不相信有“一个简单的修复”,但一般来说,“我有一行包含可变数量的元素而没有独特分隔符的文本”的原则是将其读入字符串,然后进行相关检查输入是否有1,2或3个元素(也考虑Superman 9876 4123.09作为输入)。

一种方法是计算分隔符的数量(在本例中为空格):

std:string line;
getline(fin, line);
vector<int> space_loc; 
for(int i = 0; i < line.size(); i++)
{
    // Do we have a space? 
    if (line[i] == ' ')
    {
        space_loc.push_back(i);
        // Skip multiple spaces. 
        while(i < line.size() && line[i] == ' ')
        {
        }
    }
}
if (space_loc.size() == 4) 
{
   ...  /* we have three names */
}
else if (space_loc() == 3)
{
   ... /* we only have two names */
}
... more stuff here - remember to add error handling when the data is incomplete.

我还要确保代码只执行一个read语句,而不是两个。你也许可以这样做:

nnptr = new customerType; 

... read into nnptr ... 

if( head == NULL) 
    currptr = head = nnptr;
else
    currptr->next = nnptr; 

(当输入文件中只有一条记录时,这也避免了代码出现问题)