C ++忽略输入第一个单词的简单方法
C++ Easy way to ignore first word of input
我正在编写一个程序来逐行读取文本文件,将行值存储在向量中,进行一些处理然后写回新的文本文件。文本文件通常如下所示:
如您所见,有两列:一列是帧数,另一列是时间。我想要的只是第二列(又名时间)。文本文件中可能有数百行,甚至数千行。以前我一直在手动删除我不想做的帧数列。所以我的问题是:是否有一种简单的方法来编辑我当前的代码,以便当我使用 getline()
读取文件时它会跳过第一个单词而只获取第二个单词?这是我用来读取文本文件的代码。谢谢
ifstream sysfile(sys_time_dir);
//Store lines in a vector
vector<string> sys_times;
string textline;
while (getline(sysfile, textline))
{
sys_times.push_back(textline);
}
由于每行有两个数字,因此您可以读取两个数字并忽略第一个数字。
vector<double> sys_times;
int first;
double second;
while ( sysfile >> first >> second )
{
sys_times.push_back(second);
}
std::string ignore_me;
while (sysfile >> ignore_me, getline(sysfile, textline)) {
...
这利用了逗号运算符,读取该行的第一个单词(这里将 "word" 定义为非 space 字符的连续序列),但忽略结果,然后使用 getline
阅读该行的其余部分。
请注意,对于您描述的特定数据格式,我宁愿选择 RSahu 在他们的答案中显示的内容。对于"skipping the first word and reading the rest of the line".
的问题,我的回答比较笼统
我正在编写一个程序来逐行读取文本文件,将行值存储在向量中,进行一些处理然后写回新的文本文件。文本文件通常如下所示:
如您所见,有两列:一列是帧数,另一列是时间。我想要的只是第二列(又名时间)。文本文件中可能有数百行,甚至数千行。以前我一直在手动删除我不想做的帧数列。所以我的问题是:是否有一种简单的方法来编辑我当前的代码,以便当我使用 getline()
读取文件时它会跳过第一个单词而只获取第二个单词?这是我用来读取文本文件的代码。谢谢
ifstream sysfile(sys_time_dir);
//Store lines in a vector
vector<string> sys_times;
string textline;
while (getline(sysfile, textline))
{
sys_times.push_back(textline);
}
由于每行有两个数字,因此您可以读取两个数字并忽略第一个数字。
vector<double> sys_times;
int first;
double second;
while ( sysfile >> first >> second )
{
sys_times.push_back(second);
}
std::string ignore_me;
while (sysfile >> ignore_me, getline(sysfile, textline)) {
...
这利用了逗号运算符,读取该行的第一个单词(这里将 "word" 定义为非 space 字符的连续序列),但忽略结果,然后使用 getline
阅读该行的其余部分。
请注意,对于您描述的特定数据格式,我宁愿选择 RSahu 在他们的答案中显示的内容。对于"skipping the first word and reading the rest of the line".
的问题,我的回答比较笼统