本文介绍了C ++ strtok - 多用于多个数据缓冲区的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对使用 strtok()函数没有什么问题。
我解析两个文件。 Firts我加载文件1到缓冲区。这个文件是我需要加载的第二个文件的名称。两个文件都是后行读取。我的代码如下:

I have little issue with using strtok() function.I am parsing two files. Firts I load file 1 into buffer. This file constains name of the second file I need to load. Both files are read line after line. My code looks like this:

char second_file_name[128] = { "" };
char * line = strtok( buffer, "\n" );
while( line != NULL )
{
  if ( line[0] = 'f' )
  {
    sscanf( line, "%*s %s", &second_file_name );
    LoadSecondFile( second_file_name );
  }
  // processing other lines, not relevant for question
  line = strtok( NULL, "\n" );
}

LoadSecondFile(...)函数以相同的方式工作,因此:

While the LoadSecondFile(...) function works in pretty same way, thus:

char * line = strtok( buffer, "\n" );
while( line != NULL )
{
  // process file data
  line = strtok( NULL, "\n" );
}

我的问题是,在调用 LoadSecondFile ...)函数,用于解析第一个文件的 strtok()指针会乱七八糟。而不是给我跟随第二个文件的名称的行,它给我没有 - 理解为完全废话。我得到它是正确的,这是由 strtok()指针在程序中共享,不仅是在函数中引起的吗?如果是这样,我如何备份用于解析第一个文件的 strtok()的指针,然后再使用它来解析第二个文件?

What my problem is, after calling the LoadSecondFile(...) function, the strtok() pointer used for parsing the first file gets "messed up". Instead of giving me line that follows the name of the second file, it gives me nothing - understand as "complete nonsense". Do I get it right that this is caused by strtok() pointer being shared in program, not only in function? If so, how can I "back up" the pointer of strtok() used for parsing first file before using it for parsing second file?

感谢任何建议。
Cheers。

Thanks for any advice.Cheers.

推荐答案

strtok 它保持全局状态,所以(你已经发现)你不能同时标记两个字符串。在一些平台上,有更少的邪恶变体,名称如 strtok_r strtok_s ;但是因为你正在写C ++而不是C,为什么不使用C ++库?

strtok is an evil little function which maintains global state, so (as you've found) you can't tokenise two strings at the same time. On some platforms, there are less evil variants with names like strtok_r or strtok_s; but since you're writing C++ not C, why not use the C++ library?

ifstream first_file(first_file_name);      // no need to read into a buffer
string line;
while (getline(first_file, line)) {
    if (!line.empty() && line[0] == 'f') { // NOT =
        istringstream line_stream(line);
        string second_file_name;
        line_stream.ignore(' ');           // skip first word ("%*s")
        line_stream >> second_file_name;   // read second word ("%s")
        LoadSecondFile(second_file_name);
    }
}

这篇关于C ++ strtok - 多用于多个数据缓冲区的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-03 06:31