You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

循环中的if else语句无法正常工作 | C语言技术求助

Troubleshooting Your C Loop & If-Else Issue

Let's break down the problems in your code that's blocking your if-else logic from working, plus fix some critical bugs that could cause crashes or unexpected behavior:

1. Incorrect String Comparison (The Root of Your If-Else Problem)

In C, you can't compare strings directly with == (which is what I assume you were about to write in if(item[a] ...)). That syntax compares the memory addresses of the string arrays, not the actual text content. Instead, you need to use the strcmp() function from the <string.h> header.

For example, if you wanted to check if the input item matches "Rice Cooker", you'd write:

if (strcmp(item[a], "Rice Cooker") == 0) {
    // Match found - add corresponding fee or run logic
}

Don't forget to add #include <string.h> at the top of your file to use strcmp().

2. Conflicting Array Initialization & Overwrite

You're initializing the first 5 elements of item with predefined product names, then immediately overwriting them in your loop with strcpy(item[a], inputItem). This defeats the purpose of having predefined items—if your goal is to check if the input matches an existing product, you shouldn't overwrite the predefined list. Additionally, if itemAmount exceeds 5, you'll write to item[5] (which is valid since you declared item[6][50], but this still breaks your intended logic).

3. Incorrect scanf Usage for String Input

When using scanf("%s", ...) for a char array, you don't need the & operator. The array name inputItem already decays to a pointer to its first element. Your line:

scanf("%s", &inputItem);

Should be:

scanf("%s", inputItem);

Using &inputItem passes a pointer to the entire array (type char (*)[50]) instead of a pointer to a char (type char*), which can lead to undefined behavior.

Fixed Code Example

Here's a revised version of your code that addresses these issues, with a complete if-else style check for predefined items and fee calculation:

#include <stdio.h>
#include <stdlib.h>
#include <string.h> // Added for strcmp()

int main() {
    int a, itemAmount, totalFee = 0;
    // Predefined items and their matching fees
    char item[5][50] = {"Rice Cooker", "Radio", "Iron", "Charger", "Kettle"};
    int fee[5] = {7, 3, 5, 2, 3};
    char inputItem[50];

    printf("Amount of item: ");
    scanf("%i", &itemAmount);

    // Prevent array overflow - cap item count at 5 (our predefined item limit)
    if (itemAmount > 5) {
        printf("Error: Maximum 5 items allowed.\n");
        return 1;
    }

    for(a = 0; a < itemAmount; a++){
        printf("\n%i) Item : ", a+1);
        scanf("%s", inputItem); // Fixed: removed unnecessary &

        // Check if input matches any predefined item
        int matchFound = 0;
        for (int i = 0; i < 5; i++) {
            if (strcmp(inputItem, item[i]) == 0) {
                totalFee += fee[i];
                matchFound = 1;
                printf("Added %s - Fee: %d\n", item[i], fee[i]);
                break;
            }
        }

        if (!matchFound) {
            printf("Warning: '%s' is not a recognized item. No fee added.\n", inputItem);
        }
    }

    printf("\nTotal Fee: %d\n", totalFee);
    return 0;
}

Key Improvements Explained

  • Added <string.h> to enable proper string comparison with strcmp()
  • Removed the unused rate[10] variable to clean up code
  • Fixed the scanf call for string input to avoid undefined behavior
  • Added a check to prevent array overflow if the user enters an invalid item count
  • Implemented a nested loop to match input against predefined items, with clear feedback for matches and non-matches
  • Removed the conflicting overwrite of predefined item elements to align with your likely intended logic

内容的提问来源于stack exchange,提问作者Sarah

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 09:09:19