读取文本文件:读取多个值(如果存在)

时间:2013-03-10 16:28:16

标签: c++ file-io

我在尝试将程序读取到文本文件中的行尾时遇到问题。

我正在尝试使用以下格式(空格分隔的字段)从文本文件(每行一项)读取数据:

  • house(12345)
  • 类型(A =自动或M = motorcylce)
  • 许可证(WED123)
  • 年(2012)
  • msrp(23443)

该数据将用于计算车辆登记总数。

目前程序正在读取上述格式化的所有行,但是房子可能有多个车辆,因此行上还有其他数据(除了第一个字段外)在这种情况下重复)。 例如:

111111 A QWE123 2012 13222 M RTW234 2009 9023

//     ^^^^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^^^
//        first vehicle      second vehicle

一旦我到达具有附加数据的行,程序就不会读取它并进入无限循环。如何读取行中的其他数据以到达文件末尾并从无限循环中停止程序。

#include <stdlib.h>        
#include <iostream>           
#include <fstream>

using namespace std;

int main ()                   // Function Header
{                             // Start Function
    int house;
    char  type; 
    string license; 
    int year, msrp ; 
    char ch; 

    ifstream inData; 
    ofstream outData; 

    inData.open("register.txt"); 
    outData.open("vehicle.txt"); 

    inData >> house;               // Priming Read

    while (inData) {             // Test file stream variable

        do { 
            inData >> type;         
            inData >> license; 
            inData >> year;
            inData >> msrp; 

            outData << house << type << license << year << msrp << endl; 

            ch = inData.peek();
            inData >> house;

        } while(ch != '\n');            // Check for end of line 

    }                              // End while 

    system ("Pause");      
    return 0;
}

2 个答案:

答案 0 :(得分:1)

您的程序很难检测到行尾。当它尝试读取“额外数据”但遇到下一行时,流上会发生错误,导致您无法再次阅读。

您可以通过不读取内循环中的house值来“修复”您的程序。而是在检测到行尾后读取它。

        ch = inData.peek();
        //inData >> house;          // WRONG: house might be next vehicle type

    } while(ch != '\n');            // Check for end of line 

    inData >> house;                // CORRECT

}                              // End while 

但是,更好的方法是使用getlineistringstream。首先使用getline获得整行输入。将输入放入istringstream。然后,从中获取其余数据。请参阅M. M.的版本以了解此情况。

答案 1 :(得分:0)

如果我正确理解您的问题,您可以使用以下示例。

首先阅读house然后typelicenseyearmsrp

string line;
while (getline(inData , line))
{
    istringstream iss(line, istringstream::in);

    iss >> house;
    while (iss >> type >> license >> year >> msrp)
    {
      outData << house << type << license << year << msrp << endl; 
    }
}