c - C语言中如何统计char数组中输入的字符数

标签 c arrays string io

我有一个函数,它从标准输入读取一行,然后返回用户输入的字符数。问题是我似乎不知道如何计算字符数。这是代码:

 int  inputline(char* buf, size_t bufSize)
{
    static int numRead = 0;
    int ch = 0;
    //static int totalChars = 0;
    while (numRead < bufSize - 1 && ch != '\n') {
        ch = getchar();
        if(ch == EOF){
            if(feof(stdin)){
                ch = '\n'; //treated as if the user hit return and ends loop
                puts("EOF");
            }else{
                numRead = -1;
                break; //ends loop
            }
        }else{
            buf[numRead] = ch;
            ++numRead;

    }

    if (ch == '\n') {
        buf[numRead-1] = 0; // replace newline with null terminator
    } else {
        buf[bufSize-1] = 0; // ensure buffer is properly null terminated
    }

    while (ch != '\n') {
        ch = getchar();
    }

    return sizeof(buf);
}
}

我原以为 numRead 会计算这个,但事实并非如此,我也不完全确定为什么。非常感谢任何帮助!

最佳答案

你的函数比它需要的要复杂得多。这是一个简化版本:

int inputline(char* buf, size_t bufSize)
{
   // Why did you have it static. It makes sense to be automatic.
   int numRead = 0;
   int ch = 0;

   // The logic to check for when to stop is much simpler
   while ( numRead < bufSize && ((ch = getchar()) != EOF && ch != '\n') )
   {
      buf[numRead] = ch;
      ++numRead;
   }

   // Always null terminate the buffer.
   buf[numRead] = '\0';

   // You know how many characters were stored in buf.
   // Return it.
   return numRead;
}

关于c - C语言中如何统计char数组中输入的字符数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28621947/

相关文章:

c - 按位检查有符号乘法溢出会产生意外结果

C 使用指针从矩阵中提取数组

php - 如何从php中的按钮数组中提取特定的id号?

java - 删除停用词不能正确标记

c - C中将字符串截断到一定长度,然后在末尾添加字符

javascript - JS 中在字符串前面添加不定冠词的简单方法?

c - C 是否提供 API 来以编程方式获取系统上最大可能的并发线程数?

c - 如何用C语言打开nano文件

javascript - 我如何将循环开关放入数组中?

javascript - 如何使用数组显示循环中的文本