读取和解析文件
的特定部位我有以下内容输入文件:读取和解析文件
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”,并且在下一次迭代中将是“Tend:13:58:00”。
字符串token
将成为以空格分隔的line
的一部分。所以,如果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;
啊,非常感谢。我试图在不知道哪一行是第一行,哪一行是第二行的情况下,我认为我不需要它,因为在while循环中我依次读取它。但是,我现在看到了。再次感谢。 –
感谢这篇文章的第二部分,那正是我想要的! –
你为什么使用'substr'? – LogicStuff
您没有按照您的意愿阅读文件。我怀疑你是复制了代码而没有完全理解它。如果您显示实际文件,则您执行'substr()'的第一个标记为“Tstart:”。调试器会向您显示正在读取的内容。 – stefaanv
@LogicStuff因为我只想要文件中的时间戳,而不是其他的时间戳。这是该文件中字符串的“子字符串”。 –