Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jsf-2/2.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_Strtok - Fatal编程技术网

C 检测字符数组中的行数

C 检测字符数组中的行数,c,strtok,C,Strtok,问题:我必须使用total_line-1还是只使用total_line?不需要使用strtok,因为它会修改您试图解决的问题不需要的字符串,通常是危险和糟糕的 只需循环并直接计算换行次数: char linesinfo[] = "Place\n Some\n Text\n Here"; char pch = strtok(linesinfo,"\n"); int total_line = 0; while(pch != NULL) { pch = strtok(NULL,"\n

问题:我必须使用total_line-1还是只使用total_line?

不需要使用strtok,因为它会修改您试图解决的问题不需要的字符串,通常是危险和糟糕的

只需循环并直接计算换行次数:

char linesinfo[] = "Place\n Some\n Text\n Here";

char pch = strtok(linesinfo,"\n");

int total_line = 0;
while(pch  != NULL)
{

     pch = strtok(NULL,"\n");
     total_line++;
}
这是因为C的比较运算符总是为false生成0,为true生成1。这与以下事实不同:例如,if将解释任何非零值为真,这是一个非常有用的特性

当然,上述内容可以通过多种方式重新编写,以减少简洁性,例如:

int total_line = 0;
const char *str;
for(str = linesinfo; *str; ++str)
  total_line += *str == '\n';

这可能更快,也可能更快,这取决于你的具体情况。有时,如果编译器为原始代码生成无分支的代码,那么原始代码可能会更快,我想这对于显式if来说更难。

无论您试图做什么。。但是pch应该是一个指针。
  if( *str == '\n' )
    ++total_line;