strtok 如何处理换行符?

How strtok handles newlines?

我正在尝试从包含多行的字符串中将数据作为标记读取。 我使用代码

    char * pch;
    pch = strtok ((char*)MyStr.c_str()," ,|,\n"); int i = 0;
    while (pch != NULL && i++ < 10)
    {
      cerr << i << ':' << pch << ' ';
      pch = strtok (NULL, " ,.-");
    }

输入是

std::string SP1271 = "1271,1\n"
"0,44248,8,45040,20,1,0,100\n"
"545,590,603,564,566,598,569,585,586,578\n";

输出为

1:1271 2:1
0 3:44248 4:8 5:45040 6:20 7:1 8:0 9:100
545 10:590 

使用'\n'作为分隔符是否合法?

使用 strtok() 是一个非常糟糕的主意,因为此函数可能会更改原始字符串,而原始字符串不应更改,因为它是 const

此外,即使这可行,您也没有预见到在后续 strtok() 的循环中将“\n”用作标记分隔符。因此,最好对齐所有标记分隔符字符串。

为什么不使用 C++ 功能:

size_t pe;
for (size_t pb=0; pe=MyStr.find_first_of(" ,-\n", pb); pb=pe+1)
{
    cout  << MyStr.substr(pb, (pe==string::npos ? pe:pe-pb))<< " ";
    if (pe==string::npos)
        break; 
}