【发布时间】:2015-04-09 20:25:56
【问题描述】:
我很好奇如何在C语言中正确使用%d。我目前正在学习 C 编程课程,我们遇到了一个小挑战来编辑教科书(C Programming A Modern Approach, K. N. KING)中的代码。
目标是从条形码的三个输入中编辑代码:
- 第 1 位、第 5 位和第 5 位最后一个输入,或
- 一次所有 11 位数字。
在文中解释运算符的方式中,我相信%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 个单独的数字,而只接受一个大数字。相反,它仍然需要在每个整数后按回车键。可以这样读取整数并将其分配给变量吗?
【问题讨论】:
-
将其读取为字符串,然后使用 strtok 对其进行标记
-
永远不要使用
strtok。它被彻底破坏了。 -
读取为字符串,依次取出每个字符(srtr[0],str[1],str[2],...)
-
@abelenky - 从不使用 strtok。它被彻底破坏了 - 至少引用一些东西。
strtok()没有 无可救药地坏了。最近有人引用的问题是它缺乏线程安全性。但它并不声称线程安全。那么,有什么问题呢? -
1) 要么你的编译器坏了,要么描述的事件不是这样。 2)
scanf()的返回值是多少,d的返回值是多少?