[英]Universal Product Code challenge
我很好奇如何在C语言中正确使用%d
。 我目前正在上一门C编程课程,在编写教科书中的代码方面遇到了一个小挑战(《 C编程现代方法》,KN KING)。 目的是从条形码的三个输入中编辑代码:
在文字解释操作符的方式上,我相信%1d
允许将输入的整数分别分配给相应的变量。 下面是编辑后的代码。
#include <stdio.h>
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个单独的数字,而只接受一个大数字。 取而代之的是,它仍然需要在每个整数之后命中Enter。 这样可以读取整数并将其分配给变量吗?
给定下面的代码,如果您键入“ 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 <stdio.h>
/* ... */
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语言中的字符串只是字符数组,因此您也可以遍历循环并调用string [0],string [1]等,并将它们分别转换为整数,只要您知道预先输入的长度,这给了您解释,听起来像您一样。
您的代码应该可以在gcc comliler中使用。 但是,由于它不起作用,您应该将11位数字输入到字符数组(即字符串)中,然后遍历该数组,同时将每个字符转换为相应的整数值。 您可以通过仅计算array[i]-'0'
来获取值,即d = array[0]-'0'
和i1 = array[1]-'0'
等。
好吧,我刚刚测试了以下程序:
#include <stdio.h>
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()
将其转换为相应的整数,或者如果必须/想要绝对使用scanf()
,则简单地从中减去'0'
。 否则,我要做的就是用%s
读取整个字符串,然后迭代单个字符,这在C语言中非常容易,因为字符串只是一个字符数组。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.