阅读和解析文件的特定部分

Read and parse specific parts of the file

本文关键字:定部 文件 和解      更新时间:2023-10-16

我有一个带有以下内容的输入文件:

Tstart: 13:51:45
Tend: 13:58:00

我想在最后将时间戳放在单独的字符串中。到目前为止,我已经写了以下内容:

// open the info file
    if (infile.is_open())
    {
        // read the info regarding the played video
        string line;
        while (getline(infile, line))
        {
            istringstream iss(line);
            string token;
            while (iss >> token)
            {
                string tStart = token.substr(0, 6);
                string tEnd = token.substr(7,2);
                cout << tStart << tEnd<< endl;
            }
        }
        infile.close();
    }
    else
        cout << "Video info file cannot be opened. Check the path." << endl;

我得到以下输出:

Tstart
13:51:5
terminate called after throwing an instance of 'std::out_of_range'
  what():  basic_string::substr: __pos (which is 7) > this->size() (which is 5)

我确实理解了错误所说的内容,但是我找不到在C 中这样做的另一种方法。

有人有一个主意吗?

字符串line将是文本的一行。首先是" TSTART:13:51:45",在下一个迭代中,它将是"趋势:13:58:00"。

字符串token将是由空间界定的line的一部分。因此,如果线是" tstart:13:51:45",那么令牌将是" tstart:"在第一迭代中,在第二次迭代中" 13:51:45"。这不是您需要的。

而不是内部while循环,建议使用string::find搜索一个空间,然后在 string::substr的空间之后取得所有内容:

bool is_first_line = true;
string tStart, tEnd;
while (getline(infile, line))
{
    int space_index = line.find(' ');
    if (space_index != string::npos)
    {
        if (is_first_line)
            tStart = line.substr(space_index + 1);
        else
            tEnd = line.substr(space_index + 1);
    }
    is_first_line = false;
}
cout << tStart << tEnd << endl;

如果不提前知道哪个线有哪个值,那么我们仍然可以摆脱内部循环:

string tStart, tEnd;
while (getline(infile, line))
{
    int space_index = line.find(' ');
    if (space_index != string::npos)
    {
        string property_name = line.substr(0, space_index);
        if (property_name == "Tstart:")
            tStart = line.substr(space_index + 1);
        else if (property_name == "Tend:")
            tEnd = line.substr(space_index + 1);
    }
}
cout << tStart << tEnd << endl;