今天我遇到了scanf函数的问题.假设您有一个类似于以下示例的结构.
struct structA{
bool bVal;
int nVal;
}
Run Code Online (Sandbox Code Playgroud)
如果您运行以下代码
structA a;
a.nVal = 7;
...// Assume that we read a text file and the only text is "0"
fscanf(fp,"%d",&a.bVal);
printf("\n a.bVal=%d",a.bVal);
printf("\n a.nVal=%d",a.nVal);
Run Code Online (Sandbox Code Playgroud)
它会打印出来
a.bVal = 0
a.nVal = 0
Run Code Online (Sandbox Code Playgroud)
原因是fscanf函数假定a.bVal是一个整数并覆盖a.nVal前3个字节.这个问题可以通过以下脏解决方案来解决.
structA a;
a.nVal = 7;
...// Assume that we read a text file and the only text is "0"
int nBVAL;
fscanf(fp,"%d",&nBVAL);
a.bVal = nBVAL;
printf("\n a.bVal=%d",a.bVal);
printf("\n a.nVal=%d",a.nVal);
Run Code Online (Sandbox Code Playgroud)
我的问题是,解决方案旁边是否有一种更清洁,直接的方法来避免这个问题?
小智 8
您提出的解决方案是唯一可移植的解决方案.
没有转换说明符_Bool._Bool除了它至少有CHAR_BIT位之外,也不能保证a的存储大小.即使你知道大小,并试图像%hhd,进入比其他任何事情1或0将创建一个值,该值是无效的_Bool(scanf()将通过访问对象char的指针,可能写的填充位的_Bool).
唯一安全的做法是接受你可以处理的类型的输入并将其转换为_Bool需要的地方,正如你在你的例子中所做的那样.
请注意,没有类似的问题printf().一个_Bool传递到printf()被提升到int,所以%d是好的.