質問

私が管理できない私のサイズの検証機能が正しく機能します

    void getsize(int* size, int cap){
    while(1){
    printf("Enter the size(whole number) of array from interval (0, %d]: \n", cap);
   if (scanf("%d", size) == 1){
    if ((*size > 1) && (*size <= cap)){
            printf("Size: %d entered\n", *size);
            break;
        } else {
            printf("Invalid size. Try again.\n");
        }
    } else {
        printf("Invalid size. Try again.\n");
        break;
    }
    }
}
.

私がユーザーから期待するものは正の整数を入力することです。誰もがこれを修正することができますか、これに向けてより良い解決策を示すことができますか?ありがとう。

役に立ちましたか?

解決

あなたのバージョンは、ドットが有効な整数の前の部分からフロート番号を受け入れることがあります。代わりにSTRTOLを使用して番号の末尾を確認することができます。

#include <stdio.h>
#include <stdlib.h>
void getsize(int* size, int cap){
    char buffer[256], *c;
    while (1) {
        if (fgets(buffer, sizeof(buffer), stdin)) {
            int lsize = strtol(buffer, &c, 10);
            if ((lsize > 1) && (lsize <= cap) && c[0] == '\n'){
                printf("Size: %d %s entered\n", lsize, c);
                *size = lsize;
                return;
            } 
        }
        printf("Invalid size. Try again.\n");
    }
}

int main ( ) {  
    int size;
    getsize(&size, 10);
    return 0;
}
.

他のヒント

「CAP」自体によって提供され得る制限が必要な限界を必要とするので、受信サイズを受信サイズとして使用することはできません。P>

void getsize(int cap){
   int size;
while(1){
printf("Enter the size(whole number) of array from interval (0, %d]: \n", cap);
if (scanf("%d", &size) == 1){
if ((size > 1) && (size <= cap)){
        printf("Size: %d entered\n", *size);
        break;
    } else {
        printf("Invalid size. Try again.\n");
    }
} else {
    printf("Invalid size. Try again.\n");
    break;
}
}
}
.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top