Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/150.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angular/28.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 有效地读取字符的位置_C++ - Fatal编程技术网

C++ 有效地读取字符的位置

C++ 有效地读取字符的位置,c++,C++,我有以下文本文件。每个数据字段由|分隔,行由换行符分隔 |1|data1|data2|....|....|....|\n |2|data2|data3|....|....|....|\n . . 我想收集第二个和第三个符号之间的数据字段。我的计划是找到第二个|符号的位置并读取数据直到第三个|,然后找到新行符号以重复相同的操作。我听说如果我们有位置,我们可以使用lseek函数移动光标游标。我可以一个字符一个字符地读,直到找到第二个和第三个|符号,但是我想用一种更快的方法找到新行符号。最有效的方法

我有以下文本文件。每个数据字段由|分隔,行由换行符分隔

|1|data1|data2|....|....|....|\n
|2|data2|data3|....|....|....|\n
.
.
我想收集第二个和第三个符号之间的数据字段。我的计划是找到第二个|符号的位置并读取数据直到第三个|,然后找到新行符号以重复相同的操作。我听说如果我们有位置,我们可以使用lseek函数移动光标游标。我可以一个字符一个字符地读,直到找到第二个和第三个|符号,但是我想用一种更快的方法找到新行符号。最有效的方法是什么?下面是我的源代码

  std::string str ("1|data1|data2|....|....|....|\n");
  std::string str2 ("|");
  std::size_t firstpipe = str.find(str2);
  std::size_t secondpipe = str.find(str2,secondpipe+1);
  if (found!=std::string::npos)
       std::cout << "first '|' found at: " << firstpipe << '\n';
       std::cout << "scond '|' found at: " << secondpine << '\n';
在伪代码中:

while( read line with `std::getline` into `std::string`)
    find first separator with `std::string::find`
    if not found skip line
    find second separator with `std::string::find` starting from first separator + 1
    if not found skip line
    find third separator with `std::string::find` starting from second separator position + 1
    use `std::string::substr(secondPos+1,thirdPos-secondPos-1)` to get your datablock.

使用std::getline将每条记录读入一个std::string,然后从字符串中提取值要容易得多。可能效率也更高。文件是流媒体设备。它们在传输大量数据时效率最高。因此,最有效的方法是读取文本行记录,然后搜索内存以获得所需的字段。您可能会发现读取多行或多块数据比一次读取一行更有效。而且,在内存中搜索要比在驱动器上搜索快。@ThomasMatthews我明白你的意思。我添加了一段代码并引用了该代码。我用了一根绳子。根据你的说法,我应该把这个字符串作为一个块从文件中读取。这是真的吗?搜索内存意味着我应该使用memmap?@Malintha现在您的数据文件示例与上面代码中的str变量之间存在差异。当你试着调试时,会有一种非常不舒服的感觉,你的代码不会从文件中读取。