c++ - 使用 fscanf 或等价物扫描字符串

标签 c++ file stream scanf

我已经有了一个“复杂”的程序,所以我想尽可能使用下面的代码:

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/

相关文章:

c++ - 如何检查文件是否由C++中的另一个进程使用?

java - 在 Robocode (Java) 中写入文件

c++ - 我可以在 operator= 中使用 placement new(this) 吗?

c++ - 列表框属性值未出现在 C++ 自定义操作 Wix 中?

file - Maven package 在 jar 包中打开一个文件(作为 *File*)

JAVA,通过URL播放mp3

c++ - ios::ate 不会移动到文件末尾

Node.js 可读流 _read 用法

c++ - 与 BOOST Range 的接口(interface)

c++ - 困惑如何使用 IDL 与 Ethovision 进行通信