Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/string/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/url/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在c语言中用空格扫描多维字符串_C_String_Multidimensional Array_Input_Space - Fatal编程技术网

在c语言中用空格扫描多维字符串

在c语言中用空格扫描多维字符串,c,string,multidimensional-array,input,space,C,String,Multidimensional Array,Input,Space,我想做一张简单的凭单。所以,我使用了一个多维字符串。但面临的麻烦包括那些字符串中的空格。相反,我把单词作为输入。但是有没有办法把空间包括进去呢?我的代码如下- #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",

我想做一张简单的凭单。所以,我使用了一个多维字符串。但面临的麻烦包括那些字符串中的空格。相反,我把单词作为输入。但是有没有办法把空间包括进去呢?我的代码如下-

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

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

这将在列表[i]中留下一个尾随空格,但如果不需要,可以对其进行修剪

然后,scanf呼叫可能看起来像

scanf(" %50[^0-9]%d", list[i], &amount[i]);
请注意格式字符串中的前导空格,以告知scanf跳过空白,如前一行的换行符,以及宽度说明符,使其读取的内容不超过第[i]行所能容纳的范围

当然,这会阻止您在读取的字符串中包含数字。要解决此问题,您需要采用更复杂的方法


例如,将整行读入缓冲区,然后找到字符串中的最后一个空格。然后可以将最后一个空格之前的内容复制到列表[i],并将后面的内容转换为金额[i]的int值。

但是%[]说明符在这个问题上不起作用,我不知道为什么