我撰寫了這個程式,它接受 astring作為輸入并回傳它的長度。
#include<stdio.h>
#include<string.h>
#define MAX 100
int main()
{
char a[MAX];
int len;
printf("Enter a string: ");
fgets(a, MAX, stdin);
len = strlen(a);
printf("Length of the string = %d", len);
return 0;
}
由于該函式strlen()不計算空字符,即'\0'為什么我的輸出總是比輸入的字符多 1 string?
例如 -
Enter a string: Aryan
Length of the string = 6
Process returned 0 (0x0) execution time: 4.372 s
Press any key to continue.
uj5u.com熱心網友回復:
如果提供的陣列中有空格,該函式fgets可以將換行符附加到輸入的字串。'\n'
來自 C 標準(7.21.7.2 fgets 函式)
2 fgets函式從stream指向的流中讀取最多比n指定的字符數少一個到s指向的陣列中。在換行符(保留)之后或檔案結尾之后不會讀取其他字符。在讀入陣列的最后一個字符之后立即寫入一個空字符
因此,在這個呼吁 strlen
len = strlen(a);
換行符也被計算在內。
例如,您需要將其洗掉
a[ strcspn( a, "\n" ) ] = '\0';
或者
char *p = strchr( a, '\n' );
if ( p != NULL ) *p = '\0';
uj5u.com熱心網友回復:
該fgets()呼叫包括從輸入流中讀取的換行符。這很有用,因為它允許您檢查該行是否已完全讀取。如果輸入的最后一個字符沒有換行符,則讀取的行不完整。
int main()
{
char a[MAX];
size_t len; // being precise with your types is a good habit
printf("Enter a string: ");
fgets(a, MAX, stdin);
len = strlen(a);
if ( a[len - 1] == '\n' )
{
// Usually you don't want the newline in there.
a[--len] = '\0';
// --len above corrected the length.
printf("Length of the string = %zu\n", len);
}
else
{
printf("Length of the string longer than %d\n", MAX - 1);
// You can repeat fgets() until you get the whole line,
// or keep reading (and throwing away) from input until
// you get a newline. It really depends on how you want
// to handle the error.
}
return 0;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/417885.html
標籤:
上一篇:XOR加密代碼產生錯誤結果
