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

C语言字符串与空格问题:scanf格式符%s期望char*类型参数却传入int类型的错误修复求助

Fixing the Type Mismatch Error in Your POS System Code

Hey there! Let's sort out that frustrating type mismatch error you're running into. I know pointers haven't been covered in your learning yet, so I'll keep this explanation simple and avoid jargon wherever possible.

The Root of the Problem

Your current code uses char code[items]—this is a one-dimensional array where each code[i] is a single character (which gets treated as an int under the hood). But the %s format specifier in scanf and printf expects a starting address of a string (a sequence of characters), not a single character. That's exactly why you're seeing the type mismatch error.

The Simple Fix (No Pointers Needed!)

Instead of a one-dimensional array for item codes, use a two-dimensional character array. This lets you store multiple strings (one per item code) without needing to understand pointers right now. Here's how to adjust your code:

#include <stdio.h>

int main() {
    int items;
    int i;
    // Main menu of the program
    printf("*********WELCOME TO ABC FASHION STORE***********\n");
    printf("			1.Make a new sale\n			2.Exit from POS system\n");
    printf("-----------------------------------------------------\n");
    printf("How many different types of items in your sales:");
    scanf("%d",&items);
    
    // Change to a 2D array: each row holds one item code (max 20 characters)
    char code[items][20]; 
    int qty[items];
    
    for(i=0;i<items;i++) {
        printf("Enter the item code:");
        // code[i] now points to the start of the i-th item code string
        scanf("%s", code[i]); 
        printf("Enter the quantity:");
        scanf("%d",&qty[i]);
    }
    
    // Displaying the details of the sale
    printf("\nITEM CODE \t\t QUANTITY \t\t UNIT PRICE \t\t TOTAL\n");
    for(i=0;i<items;i++) {
        // code[i] works here too, since it's the start of the string
        printf("%s\t\t%d\t\t\n", code[i], qty[i]);
    }
    
    return 0;
}

Key Changes Explained

  • char code[items][20];: This creates a "table" where each row (code[0], code[1], etc.) is a string that can hold up to 20 characters (adjust the 20 if your item codes are longer/shorter).
  • scanf("%s", code[i]) and printf("%s", code[i]): Now code[i] refers to the starting position of the i-th item code string, which is exactly what %s needs to read and print the full code.

This fix works perfectly without needing to learn pointers first, and it keeps your code structure simple for your current level of learning.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.29 10:29:08