【问题标题】:Scanning multidimensional string with space in c用c中的空格扫描多维字符串
【发布时间】:2020-06-26 21:28:13
【问题描述】:

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

#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】:

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

    这将在list[i] 中为您留下一个尾随空格,但如果您不想要,可以将其删除。

    scanf 调用可能看起来像

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

    注意格式字符串中的前导空格,告诉scanf 跳过空格(如上一行的换行符),并且宽度说明符不能读取超过line[i] 的内容。

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

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

    【讨论】:

    • 但是 %[] 说明符在这个问题中不起作用我不知道为什么
    猜你喜欢
    • 1970-01-01
    • 2012-01-28
    • 1970-01-01
    • 2014-12-29
    • 2016-07-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-14
    相关资源
    最近更新 更多