通用产品代码挑战

我很好奇如何在C语言中正确使用%d 。 我目前正在修读C编程课程,我们在编写教科书中的代码时遇到了一个小小的挑战(C编程现代方法,KN KING)。 目标是从条形码的三个输入编辑代码:

  • 第一个数字,第五个数字和第五个数字为最后一个输入,或
  • 一次全部11位数。

在文本解释运算符的方式中,我认为%1d允许将输入的整数单独分配给相应的变量。 以下是编辑过的代码。

 #include  int main(void) { /* 11 integers that come from the bar code of the product, then 2 intermediate variables for calulation, and lastly the final answer.*/ int d, i1, i2, i3, i4, i5, j1, j2, j3, j4, j5, first_sum, second_sum, total; printf("Enter the 11 digit Universal Product Code: "); scanf("%1d%1d%1d%1d%1d%1d%1d%1d%1d%1d%1d", &d, &i1, &i2, &i3, &i4, &i5, &j1, &j2, &j3, &j4, &j5); // The steps for each calculation from the textbook. first_sum = d + i2 + i4 + j1 + j3 + j5; second_sum = i1 + i3 + i5 + j2 + j4; total = 3 * first_sum + second_sum; // Prints check digit for given product code. printf("Check Digit: %d\n", 9 - ((total-1) % 10)); return 0; } 

但是,当我运行程序时(与原始程序相同的问题),它不接受11位数输入作为11个单独的数字,仅作为一个大数字。 相反,它仍然需要在每个整数后命中输入。 可以通过这种方式读取整数并将其赋值给变量吗?

根据下面的代码,如果您键入“123”然后按Enter键,它将打印“1 2 3”。

 int main( void ) { int a, b, c; printf( "Enter a three digit number\n" ); if ( scanf( "%1d%1d%1d", &a, &b, &c ) != 3 ) printf( "hey!!!\n" ); else printf( "%d %d %d\n", a, b, c ); } 

也就是说%1d将一次读取一位数。


以下示例来自C11规范草案的第7.21.6.2节

 EXAMPLE 2 The call: #include  /* ... */ int i; float x; char name[50]; fscanf(stdin, "%2d%f%*d %[0123456789]", &i, &x, name); with input: 56789 0123 56a72 will assign to i the value 56 and to x the value 789.0, will skip 0123, and will assign to name the sequence 56\0. The next character read from the input stream will be a. 

这是它一直以来的方式,所以如果你的编译器不这样做,你需要得到一个新的编译器。

对你的问题的简短回答是否定的。 除非字符串中存在某种分隔空格,否则%d标记将获取它可以获得的最大整数,而不仅仅是单个数字。

解决这个问题的一般方法是将输入作为字符串读取,然后使用strtok等对输入进行标记。

但是,因为在C字符串中只是字符数组,所以你也可以遍历一个循环并调用字符串[0],字符串[1],依此类推,只要你知道就把它们分别变成一个整数。预先输入的长度,给出你的解释听起来就像你做的那样。

好吧,我刚刚测试了以下程序:

 #include  int main (void) { int n, x, y, z; n = sscanf ("1234567890", "%1d%1d%1d", &x, &y, &z); printf ("Found %d items: %d, %d and %d\n", n, x, y, z); return 0; } 

我在Slackware Linux下编译它,库存GCC和glibc。 它输出:

共找到3项:1,2和3

因此,它似乎应该按照您希望的方式工作,但我不确定这是否实际上是标准行为,或者更确切地说是GCC扩展。

另一种方法是使用%1c一次读取一个字符,然后使用atoi()将其转换为相应的整数,或者简单地从中减去'0' ,如果必须/想要绝对使用scanf()那样。 否则,我要做的是用%s读取整个字符串然后迭代单个字符,这在C中非常容易,因为字符串只是一个字符数组。

您的代码应该在gcc comliler中工作。 但是,由于它不起作用,您应该将11位数字输入字符数组(即字符串),然后迭代数组,同时将每个字符转换为其对应的整数值。 您可以通过计算array[i]-'0'得到该值,即d = array[0]-'0'i1 = array[1]-'0'等等。