我已经有了一个“复杂”的程序,所以我想尽可能使用下面的代码:
const char* path = filename.c_str();
FILE * file = fopen(path, "r");
if( file == NULL ) {
printf("Obj File was not found");
return 0;
} else {
std::ifstream input(path);
std::string line;
while( std::getline( input, line ) ) {
string sub;
iss >> sub;
// here i read in a lot of lines which are in sub
}
}
现在我需要像这样分隔一行:
f 2/3/1 3/4/1 4/6/1
并找到了 fscanf,它应该像这样工作
fscanf(file, "%d/%d/%d %d/%d/%d %d/%d/%d\n", &a, &b, &c, &d, &e, &f, &g, &h, &i);
但是"file"必须是一个文件。我如何将一个字符串(在本例中为 sub)输入到 fscanf 中,或者是否有另一种简单的解决方案来尽可能短地读取这一行。
最佳答案
你需要 sscanf() 函数。
sscanf(sub, "%d/%d/%d %d/%d/%d %d/%d/%d\n", &a, &b, &c, &d, &e, &f, &g, &h, &i);
关于c++ - 使用 fscanf 或等价物扫描字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34537241/