簡體   English   中英

為什么每次我輸入 10 進行評級輸入時,我的 C 代碼 output 垃圾值?

[英]Why my C code output garbage value each time i enter 10 for rating input?

#include <stdio.h>
#include <string.h>

struct Food{
    char* item;
    int rating;
    char reason[30];
    char histogram[11];
};

void removeNewline(char* x){
    char temp[30];
    for(int i = 0; i < strlen(x)-1; i++){
        temp[i] = x[i];
    }
    temp[strlen(x)-1] = '\0';
    
    strcpy(x, temp);
}

int main()
{
    struct Food x[10];

    x[0].item = "Burger";
    x[1].item = "Broast";
    x[2].item = "Rice";
    x[3].item = "Roll";
    x[4].item = "Handi";
    x[5].item = "Platter";
    x[6].item = "Kebabs";
    x[7].item = "Sandwich";
    x[8].item = "Shake";
    x[9].item = "Kheer";

    char sum[10];
    for(int i = 0; i < 2; i++){
        printf("\nEnter score for %s (1 - 10) : ", x[i].item);
        scanf("%d", &x[i].rating);
        fflush(stdin);

        printf("Enter reason for liking or disliking : ");
        fgets(x[i].reason, 30, stdin);
        removeNewline(x[i].reason);

        strcpy(sum, "*");
        for(int j = 1; j < x[i].rating; j++){
            strcat(sum, "*");
        }
        strcpy(x[i].histogram, sum);
    }

    printf("\n%-13s%-11s%-35s%s\n", "Item", "Rating", "Reason", "Histogram");
    for(int i = 0; i < 2; i++){
        printf("%-13s%-11d%-35s%s\n", x[i].item, x[i].rating, x[i].reason, x[i].histogram);
    }
    
    return 0;
}

每當我為評級輸入輸入值 10 時,Output 就帶有垃圾值

為什么我的 output 每次輸入 10 進行評分時都會顯示垃圾值? 任何 C 專家可以提供幫助嗎? 任何 C 專家可以提供幫助嗎? 任何 C 專家可以提供幫助嗎? 任何 C 專家可以提供幫助嗎? 任何 C 專家可以提供幫助嗎? 任何 C 專家可以提供幫助嗎? 任何 C 專家可以提供幫助嗎? 任何 C 專家可以提供幫助嗎?

這是刪除換行符的更快方法。

name[strlen(name) - 1 = '\0';

其中 name 是字符數組。

在您要求用戶輸入 1-10 的地方,您可能想從中減去,以處理從零開始的數組。

希望這能解決您的問題!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM