阅读和解析文件的特定部分
Read and parse specific parts of the file
我有一个带有以下内容的输入文件:
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;
相关文章:
- .cpp和.h文件中的模板专用化声明
- 为什么两个不同的未命名名称空间可以共存于一个cpp文件中
- 文本文件中的单词链表
- CMake-按正确顺序将项目与C运行时对象文件链接
- 使用新行和不使用新行读取文件
- 不同的数学符号绑定与共享库与 dlopen 并直接链接到可执行文件 (Linux)
- 提升 ASIO 绑定:错误的文件描述符
- 如何使用Python绑定到Clang来解析单个文件
- 尽管模板是静态绑定的,但旧代码的对象文件为什么以及如何使用使用通用编程范式的新代码
- 一次从文件中读取多行而不读取部分行的方法
- 错误:无法在实现文件中绑定“std::ostream”
- 代码合成XSD解析/数据绑定xml字符串,而不是xml文件
- 顶级qml文件中的Repeater元素导致QtQuick 1.1(QtCreator 3.5.1)中的绑定循环
- 使用OpenCL 2.0 c++绑定头文件的链接器错误
- 如何在c++文件中使用opencv函数并将其与Python绑定
- 从文件中读取字符串并将其不同部分保存在C++中的不同变量中
- cpp 文件中的部分行最终出现在输出文件中 - 闹鬼的代码
- c++ makefile:只使用include目录中的部分头文件
- 解析get中的cpp文件时筛选目录包含在python绑定/clang中
- 在完成游戏编程后,如何在可执行文件中绑定资产并将其打包,以便分发给其他人