我正在编写一个程序,它接受这样一个 txt 文件:
foo.txt:
Aaaa/NGACG/NGAA//
Aaab/AGGGC//
Aaac/CTN/AGGC/NNA//
并且在每一行中,它将 ID (Aaa..) 存储到一个 vector 中(每个值一次),并将值以/分隔到字符串中。
所以第一行是:
foo.push_back("Aaaa");
string bar = NGACG;
foo.push_back("Aaaa");
string bar2 = NGAA;
伪代码是这样的:
while (not end of file)
{
while (not end of line)
{
while (next char isn't /)
{
temporary string x += char
}
foo.push_back(string) //ID
while (next char isn't /)
{
string bar += char //value
}
}
}
我的伪代码显然有缺陷,但这是我想做的事情的总体思路。我查阅了有关如何解析的指南,但对我的目的没有任何帮助。我怎样才能做到这一点而不会完全低效?如果不使用任意数量的 while 循环,我想不出如何写这个
最佳答案
您可以使用fgets
和strtok
以古老的C 方式做到这一点:
char line[SIZE]; // make sure SIZE is greater than your longest input line ...
char *ix;
while(fgets(line), SIZE, fdin) {
line[strcspn("\n")] = '\0'; // remove EOL
ix = strtok(line, "/");
foo.push_back(string(ix));
string bar = string(strtok(NULL, "/"));
string bar2 = string(strtok(NULL, "/"));
...
}
或者您可以使用带有分隔符参数的 stringstream
和 std::getline
:
string line;
while(getline(fdin, line)) {
string temp, bar, bar2;
istringstream is(line);
getline(is, temp, '/');
foo.push_back(temp);
getline(is, bar);
getline(is, bar2);
...
}
当然,您应该为错误条件添加测试...
关于c++ - 按分隔符拆分行以解析文本文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32904008/