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