我很好奇如何在C语言中正确地使用%d
。我目前正在上C编程的课程,我们被赋予了一个小的挑战来编辑教科书中的代码(C编程--现代方法,K.N.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。可以这样读取整数并分配给变量吗?
发布于 2015-02-09 22:57:43
给定下面的代码,如果您键入"123“,然后按enter键,它将打印”12,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.
这种情况一直是这样的,所以如果编译器不这样做,就需要一个新的编译器。
发布于 2015-02-09 23:03:54
对你问题的简短回答是否定的。%d标记将获取它能够获取的最大整数,而不仅仅是单个数字,除非字符串中有某种类型的分隔空间。
解决这一问题的一般方法是将输入读入为字符串,然后使用strtok等来标记输入。
但是,由于在C中字符串只是字符数组,所以您也可以遍历一个循环并调用string、string1等,并且只要事先知道输入的长度,就可以将每个字符串分别转换为整数,这给出了您的解释--听起来就像您所做的那样。
发布于 2015-02-09 23:09:06
您的代码应该在gcc通信程序中工作。但是,由于不起作用,您应该将11位数字转换为字符数组,即字符串,然后遍历数组,同时将每个字符转换为相应的整数值。在您的情况下,只需计算array[i]-'0'
、即d = array[0]-'0'
和i1 = array[1]-'0'
等就可以得到值。
https://stackoverflow.com/questions/28420931
复制相似问题