用c中的空格扫描多维字符串

问题描述 投票:0回答:1

我正在尝试制作一张简单的凭单。因此,我使用了多维字符串。但是面临麻烦,包括那些字符串中的空格。相反,我将单词作为输入。但是有什么办法可以容纳空间吗?我的代码如下-

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

int main(){

    int sum =0, n, i;
    puts("Please input how many transactions you want to enlist: ");
    scanf("%d", &n);
    char list[301][51];
    int amount[301];
    puts("Please enter the name of your transaction and the amount: (Press space or enter to toggle between name and amount . And avoid using spaces in the name; use underscore instead.)");
    for(i=0; i<n; i++){

        scanf("%s %d", &list[i], &amount[i]);
        sum += amount[i];
    }
    list[0][n+1] = '\0';
    amount[n+1] = '\0';
    puts("");
    printf("\t\t\t\t Voucher\n\n");
    puts("  Ser.|\t Name \t\t\t\t\t\t\t|Amount");
    puts("------------------------------------------------------------------------------------------------------------");
    for(i=0; i<n; i++ ){
        printf("  %03d |\t %-50s\t|%6d\n", i+1, list[i], amount[i]);
    }
    puts("------------------------------------------------------------------------------------------------------------");
    printf("      |  Total\t\t\t\t\t\t\t|%6d", sum);
    puts("");
    return 0;
}
c string multidimensional-array input space
1个回答
0
投票

为此,您可以使用%[ scanf说明符读取所有字符,直到您击中一个数字,然后将其写入scanf

[这会在list[i]中留下尾随空格,但是如果您不想要,可以将其修剪掉。

list[i]调用可能看起来像

scanf

请注意格式字符串中的前导空格,以告诉scanf(" %50[^0-9]%d", list[i], &amount[i]); 跳过空格(如前一行的换行符,并且宽度说明符的读入内容不能超过scanf的大小。

© www.soinside.com 2019 - 2024. All rights reserved.