如何计算在C中的char数组中输入的字符数

时间:2015-02-20 05:04:03

标签: c arrays string io

我有一个从stdin读取一行的函数,然后返回用户输入的字符数。问题是我似乎无法弄清楚如何计算字符数。这是代码:

 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会算这个,但事实并非如此,而且我并不完全确定原因。任何帮助都非常感谢!

1 个答案:

答案 0 :(得分:0)

你使你的功能变得比它需要的复杂得多。这是一个简化版本:

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;
}