我创建了一个函数来计算字符串第一行的字符数。如果字符串只有一行,那么它将计算字符数,直到终止的空\ 0。将ch字符与\ n比较的部分按预期工作,但我无法成功将ch字符与\ 0比较。即使我在字符串中添加了多个\ 0,它也永远无法满足比较要求。任何想法?

#include <stdio.h>

int main() {
    /*variables*/
    char* string="shit\nand\npee\0";
    int bytesRead=0;
    int bytesTemp=0;
    char ch=' ';

    /*find the number of characters before a newline or end of string*/
    while(ch!='\n') { //doesn't work with ch!='\0'
        sscanf(string+bytesRead, "%c%n", &ch, &bytesTemp);
        bytesRead+=bytesTemp;
        printf("Bytes read: %d\n", bytesRead);
        printf("Variable ch has value: %c\n", ch);
    }
    return 0;
}

最佳答案

问题是您没有测试sscanf的返回值。如果失败,ch将不会更新,因此您将获得最后一个符号两次,然后读取字符串的末尾。

尝试类似的东西:

if (sscanf(string+bytesRead, "%c%n", &ch, &bytesTemp) != 1)
  break;

10-07 19:46
查看更多