如何在C中获得标准输入的长度?

我将从我的代码开始:

char input[40]; fgets( input, 40, stdin ); if( checkPalin(input) == 0 ) { printf("%s ist ein Palindrom \n", input); } else { printf("%s ist kein Palindrom \n", input); } 

我想要做的是:阅读一些标准输入并检查我的function,如果它是Palindrome。

我的问题如下:如何获得标准输入的长度? 因为如果它大于40个字符我想要一个错误消息,而且我希望我的字符数组是实际输入的确切长度。

有人可以帮帮我吗?

fgets( input, 40, stdin );

输入长度不应超过40个字符== 39个字符+ nul字符

如果给出长度超过39个字符的字符串,则fgets()会先读取39个字符,并将nul character('\0')为40个字符,并忽略其余字符。

如果你给字符串少于39个字符,例如5,那么它将读取换行符,长度也变为6(不包括空字符)

别忘了删除换行符。

 char input[60]; fgets(input,sizeof input,stdin); 

例如,如果您声明输入缓冲区大小为60,那么您是否要对超过40个字符进行错误检查。

您只需检查strlen()并检查长度是否超过40.然后显示错误消息

如果要使用fgets()检查错误,请检查NULL

没有任何function可以做,你需要自己编写。 即,逐字节读取寻找EOF字符。 但我猜你这样做是为了避免溢出,对吧? 如果输入大于40字符,则不需要因为保证这样的额外值不会被fgets()函数放入缓冲区,它永远不会大于您请求的大小:40。值可能更小 – 或等于,但绝不大于。

编辑:

通过“如何在C中获得标准输入的长度?” 我在想你在谈论stdin有多少字节。 对不起,我很抱歉。 如果你想获得写入fgets()字节数,请使用strlen()

fgets( input, 40, stdin );

保证input的字符数小于等于40(包括空终止)

您不必执行检查。

并且为了获得input大小,您始终可以在input使用strlen()函数,因为来自fgets的生成的字符串始终为null终止。

事实certificate,编写一个重复使用fgets()以返回malloc() ed字符串的函数并不容易。

该函数没有正确的错误报告:如果使用realloc()fgets()发生错误,则返回到目前为止检索的数据。

除此之外,该functioncertificate非常实用。

 #include  #include  #include  char * read_one_line(FILE * in) { size_t alloc_length = 64; size_t cumulength = 0; char * data = malloc(alloc_length); while (1) { char * cursor = data + cumulength; // here we continue. char * ret = fgets(cursor, alloc_length - cumulength, in); printf("r %p %p %zd %zd %zd\n", data, cursor, cumulength, alloc_length, alloc_length - cumulength); if (!ret) { // Suppose we had EOF, no error. // we just return what we read till now... // there is still a \0 at cursor, so we are fine. break; } size_t newlength = strlen(cursor); // how much is new? cumulength += newlength; // add it to what we have. if (cumulength < alloc_length - 1 || data[cumulength-1] == '\n') { // not used the whole buffer... so we are probably done. break; } // we need more! // At least, probably. size_t newlen = alloc_length * 2; char * r = realloc(data, newlen); printf("%zd\n", newlen); if (r) { data = r; alloc_length = newlen; } else { // realloc error. Return at least what we have... // TODO: or better free and return NULL? return data; } } char * r = realloc(data, cumulength + 1); printf("%zd\n", cumulength + 1); return r ? r : data; // shrinking should always have succeeded, but who knows? } int main() { char * p = read_one_line(stdin); printf("%p\t%zd\t%zd\n", p, malloc_usable_size(p), strlen(p)); printf("%s\n", p); free(p); }