C++逐行读取文件,有些行的列与其他行不同

标签 c++ multiple-columns readfile skip

我的 text.txt 看起来像这样:

1   52  Hayden Smith        18:16   15  M   Berlin
2   54  Mark Puleo          18:25   15  M   Berlin
3   97  Peter Warrington    18:26   29  M   New haven
4   305 Matt Kasprzak       18:53   33  M   Falls Church
5   272 Kevin Solar         19:17   16  M   Sterling
6   394 Daniel Sullivan     19:35   26  M   Sterling
7   42  Kevan DuPont        19:58   18  M   Boylston
8   306 Chris Goethert      20:00   43  M   Falls Church

问题是,对于第三行,城镇的名称是 New Haven,New 和 haven 之间有一个空格。同样对于四号线,Falls 和 Church 之间有一个空间。当我逐行读取文件时,这会产生问题。

所以,我的代码是这样的:

ifstream infile("text.txt", ios::in);
if(!infile)
{
    cerr<<"File could not be opend"<<endl;
}

SortedLinked mylist;

int a;
int b;
string c;
string d;             // I have eight different variables, representing
string e;             // each column, but some lines have nine columns.
int f;                   
char g;
string h;

string mystr;
int mymin;
int mysec;

while(infile>>a>>b>>c>>d>>e>>f>>g>>h)
{

   // This does not work, because as you get to line three, h is New, there
   // is no variable to store Haven. Therefore my code can only get to line 
   // 3. 

    mystr = c+d;
    mymin = convertString<int>(e.substr(0,2));
    mysec = convertString<int>(e.substr(3, 4));


    Runner M(mystr, f, mymin, mysec);
    //M.print();
    mylist.additem(M);


}

此外,如果您尝试这样做:

replace(h.begin(), h.end(), ' ', '_')

试着在New和haven之间加一个下划线,不行。 因为这试图用另一个变量替换一个变量,这里的 h 是 New,它不是 New haven,你无法到达 haven,因为 haven 是另一个变量。所以你没有办法用下划线替换空格。

此外,如果您尝试这样做:

while(infile>>a>>b>>c>>d>>e>>f>>g>>h>>i)

这也行不通,因为当您到达第 1 行时,只有正确的列,没有任何内容可存储到变量 i 中。像这样的代码只会让您到达第 1 行。

如果您有其他方法可以做到这一点,例如跳过城镇名称列、第 8 列和第 9 列(对于某些行),因为我什至不需要城镇名称。

或者,您可以去掉 New haven 和 Fall Church 之间的空间。任何事情都会受到赞赏。

最佳答案

您可以使用 getline 读取该行的其余部分。

while( (infile>>a>>b>>c>>d>>e>>f>>g) && getline(infile, h))

关于C++逐行读取文件,有些行的列与其他行不同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35820480/

相关文章:

c - C中逐行读取并存储到数组

c++ - Delphi typcast tlist items C++ 方法

C++三元运算符,有什么区别?

c++ Vector,每当它在堆栈上扩展/重新分配时会发生什么?

mysql - 我需要在同一个表中的每个日期查询多个列

javascript - exceljs 节点模块读取 .xls 文件时出错

c++ - 静默接受 .pfx 证书

mysql - 按匹配变量的多列排序

HTML 表格 - 固定和多个可变列宽

java - 如何在 Spring MVC 应用程序中从我的 Tomcat 文件夹中的 bin 目录中读取文件?