【问题标题】:Reading text file: Read multiple values if present读取文本文件:读取多个值(如果存在)
【发布时间】:2013-03-10 16:28:16
【问题描述】:

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

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

  • 房子 (12345)
  • 类型(A = 汽车或 M = 摩托车)
  • 许可证 (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;
}

【问题讨论】:

标签: c++ file-io


【解决方案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. 的版本以了解这一点。

【讨论】:

  • 感谢 user315052,感谢您的解释。
【解决方案2】:

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

如果先读取house,然后读取type,license,year,msrp

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; 
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-01-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多