[英]C program to limit the count of characters entered by user. Need Solution?
[英]program calculates how many printable characters are in an array of characters that entered by user
我得到了錯誤的結果。 我不確定是什么導致了問題。 任務是計算用戶輸入給出的字符數組中可打印字符的數量。 無論給出什么輸入,輸出r
始終等於 0(零)。
printf("Geben sie bitte einen Zeichenkette ein \n");
fgets(s1, sizeof(s1), stdin);
int r=0;
int size = sizeof(s1)/sizeof(s1[0]);
for (i=0;i<=size;i++){
char a=s1[i];
int h = (int)a;
if (isprint(h)==1){
r=r++;
}
}
printf("%d\n",r);
return 0;
if (isprint(h)==1){ // Why compare against 1? What does that do?
r=r++; // Do you know how ++ works?? Read about it.
}
if (isprint(h)) {
r++;
}
主要問題是:輸入長度的錯誤計算(使用 strlen 而不是緩沖區大小),變量r
錯誤遞增( r =
r++ invokes undefined behaviour), and invalid assumptions on the return value of
isprint()` invokes undefined behaviour), and invalid assumptions on the return value of
(它不需要為 1 為真)。
現在,如果我們把它們放在一起,固定版本是:
char s1[BUFSIZE];
int i, r = 0;
printf("Geben sie bitte einen Zeichenkette ein\n");
fgets(s1, sizeof(s1), stdin);
for (i = 0; i < strlen(s1); i++) {
if (isprint(s1[i]))
r++;
}
printf("%d\n", r);
這個說法
r=r++;
調用未定義的行為。
這個循環
int size = sizeof(s1)/sizeof(s1[0]);
for (i=0;i<=size;i++){
當存儲的字符串的大小小於字符數組的大小時,也可以調用未定義的行為。 而且還試圖訪問字符數組之外的內存。
在本聲明中
int h = (int)a;
您必須將字符 a 轉換為 unsigned char 類型。
int h = ( unsigned char )a;
您需要我們的以下內容
printf("Geben sie bitte einen Zeichenkette ein \n");
fgets(s1, sizeof(s1), stdin);
int r=0;
for ( i = 0; s1[i] != '\0'; i++ )
{
r += isprint( ( unsigned char ) s[i] ) != 0;
}
printf("%d\n",r);
return 0;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.