首页 > 解决方案 > 用c中的空格扫描多维字符串

问题描述

我正在尝试制作一个简单的代金券。所以,我使用了多维字符串。但是面临包括这些字符串中的空间在内的麻烦。相反,我将单词作为输入。但是有没有办法包含空间?我的代码如下 -

#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;
}

标签: cstringmultidimensional-arrayinputspace

解决方案


为此,您可以使用说明%[ scanf符来读取所有字符,直到您碰到一个数字,然后将其写入list[i].

这会给你留下一个尾随空格list[i],但如果你不想要它可以修剪。

然后scanf调用可能看起来像

scanf(" %50[^0-9]%d", list[i], &amount[i]);

请注意格式字符串中的前导空格,以告知scanf跳过空格(如上一行中的换行符),以及宽度说明符不超过可以容纳的内容line[i]

当然,这会阻止您在读取的字符串中包含数字。要解决这个问题,你需要走一条更复杂的路线。

例如通过将整行读入缓冲区,然后找到字符串中的最后一个空格。然后,您可以将最后一个空格之前的内容复制到list[i],并将之后的内容转换为 的intamount[i]


推荐阅读