逐行读取文件并存储不同的变量

read file line by line and store different variables

我的文本文件如下所示:

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
9     262   James Sullivan      20:12   28  M   Sterling
10    348   Bill Gaudere        20:17   54  M   Hudson
11    13    Travis Wheeler      20:23   31  M   Clinton
12    69    Eric Anderson       20:34   54  M   Clinton
13    341   Alex Teixeira       20:46   0   M   Clinton
14    112   James Long          20:50   38  M   0
15    279   Nate Richards       21:31   17  M   Berlin
......................................................

共有八列,由 'tabs' 分隔,除了名字和姓氏由 space 分隔。

我必须有八种不同类型的变量。

    int a;
    int b;
    string c;
    string d;
    string e;
    int f;
    char g;
    string h;

我需要逐行读取文件并计算出每一行的a、b、c、d、e、f。 我还需要这些变量供以后使用。

所以,我尝试了这个:

std::ifstream infile("text.txt");
int a;
int b;
string c;
string d;
string e;
int f;
char g;
string h;


while(infile>>a>>b>>c>>d>>e>>f>>g>>h)
{
    cout <<"C is: "<<c<<endl;   // just to see if the loop is working.

}

我不需要数组和向量来存储这些变量,我有一个链接结构。现在,我只需要一种方法来读取文件并将这些字符串和整数存储到变量中。 但它不起作用,大声笑。不知道为什么。我也考虑过使用getline,像这样:

while(getline(infield, s)):

但是,这本质上不是给我一大段粗线,所有字符串和整数都混在一起了。

在我的机器上测试时,您的方法完全符合您的要求,除了它会在第三个条目处停止:

3     97    Peter Warrington    18:26   29  M   New haven

这是因为 New haven 中的 space 会导致 while 条件失败,因为它无法在下一次迭代中复制到整数字段 a 中。如果你想保留这个结构,也许用下划线代替 spaces。否则移动到逐行解析它,也许使用 std::regex 库。

例如,将位置字符串更改为由下划线而不是 spaces 分隔会导致找到所有 15 个条目。要将下划线改回 spaces,我们可以使用 std::replace,这样您的 while 循环的主体将看起来像 lile:

std::cout <<a<<" "<<b<<" "<<c<<" "<<d<<" "<<e<<" "<<f<<" "<<g<<" ";
std::replace( h.begin(), h.end(), '_', ' ' );
std::cout<<h<<"\n";

(确保包含 algorithm

我们现在已经全部打印出来了!

直接回答你原来的问题,我猜这个文件不存在。

std::ifstream infile("text.txt");
if(!infile.is_open()) {
     std::cout<<"Couldn't find file";
     return 0;
}
// ..