我应该使用哪种格式:scanf \ string,string,int,int /?

时间:2015-06-13 21:07:46

标签: c

我的数据格式为\a,b,c,d/,其中a,b是字母和数字的字符串; c,d是整数。

我尝试使用格式\%s,%s,%d,%d/格式进行扫描,但这会导致a,b,c,d/被扫描到第一个字符串而不是仅扫描一个字符串。

问题:

为了达到预期的效果,我可以输入格式吗?

3 个答案:

答案 0 :(得分:4)

您可以使用以下格式字符串将逗号用作分隔符:

"\\%[^,],%[^,],%d,%d/"

每个字符串的想法是tell scanf to read anything that isn't a comma,然后读取分隔符并继续。

这是一个(坏的和不安全的!)示例:

char a[100], b[100];
int c=0, d=0;

scanf("\\%[^','],%[^','],%d,%d/", a, b, &c, &d);
printf("%s, %s, %d, %d\n", a, b, c, d);

在实际代码中,您需要编写更安全的内容。例如,use fgets to read a full line of input可以使用sscanf重用相同的格式字符串来解析它。

答案 1 :(得分:2)

仔细阅读fscanf(3)的文档。

您可以尝试类似

的内容
char str1[80];
char str2[80];
memset (str1, 0, sizeof(str1));
memset (str2, 0, sizeof(str2));
int  n3 = 0, n4 = 0;
int pos = -1;
if (scanf ("\\ %79[A-Za-z0-9], %79[A-Za-z0-9], %d, %d /%n",
           str1, str2, &n3, &n4, &pos) >= 4
    && pos > 0) {
   // be happy with your input
 }
 else {
   // input failure
 }

如果您有更广泛的字母概念,例如法语é或俄语Ы,那么这项工作将无法奏效。两者都是UTF-8中存在的单个字母,但以几个字节表示。

我在格式字符串中添加了一些空格(主要是为了提高可读性)(但是scanf通常也会跳过空格,例如%d)。如果您不接受空格 - 如\AB3T, C54x, 234, 65/之类的输入行,请使用getline(3)fgets(3)读取每一行并手动解析(可能在{{1}的帮助下}和sscanf ...)。请注意strtol正在跳过空格!我也正在清除变量以获得更多确定性行为。请注意,%d为您提供了读取字符数(实际上是字节数!),%n返回扫描项目数。

答案 2 :(得分:-2)

我直截了当的解决方案:

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

int main()
{
    char a[10010];

    gets(a);
    int l = strlen(a);

    char storded_first[10010], storded_second[10010];
    char for_int_c[10010], for_int_d[10010];
    int c,d;

    char first_symbol, last_symbol;
    int i;
    int cnt = 0;
    int j=0;

    for(i=0; i<l; i++)
    {
        if(a[i]=='\\')
            first_symbol = a[i];
        else if(a[i]=='/')
            last_symbol = a[i];

        else if(a[i]==',')
        {
            cnt++;
            j=0;
        }

        else if(cnt==0)
        {
            storded_first[j]=a[i];
            j++;
        }
        else if(cnt==1)
        {
            storded_second[j]=a[i];
            j++;
        }
        else if(cnt==2)
        {
            for_int_c[j]=a[i];
            j++;
        }
        else if(cnt==3)
        {
            for_int_d[j]=a[i];
            j++;
        }
    }

    c = atoi(for_int_c);
    d = atoi(for_int_d);


    printf("%c%s, %s, %d, %d%c\n",first_symbol, storded_first, storded_second, c, d, last_symbol);

    return 0;
}