英文:
how variable with data type bool accept store in string bool x="hallo"; no error happen
问题
假设非零值会隐式转换为布尔值,表示数字1
x 是 1
为什么在输入相同的文本值时,它没有被视为真布尔值,就像第一个情况一样?
英文:
It is assumed that the non-zero value is implicitly converted into a Boolean value, which represents the number 1
#include <iostream>
using namespace std;
int main() {
bool x="ahmed";
cout << x<< "\n";
return 0;
}
output:
x is 1
using namespace std;
int main() {
bool x;
cin>>x;
cout << x<< "\n";
return 0;
}
output:
x is 0
Why, when entering the same text value, was it not considered as a true boolean value, as was the case in the first case?
答案1
得分: 1
以下是翻译的内容:
如评论中所述,你在比较苹果和橙子。你的代码的两个版本做了完全不同的事情。第一个涉及到数组到指针的衰变和指针到布尔值的转换,而另一个则完全不是关于这个的。第二个是关于从输入流中进行格式化提取。
这里
bool x="ahmed";
const char[6]
衰变成了 const char*
,随后被转换为 bool
。空指针转换为 false
,而其他指针转换为 true
。因此你得到了 1
作为输出。
在这里
bool x;
cin>>x;
情况更为复杂。你调用了 std::istream::operator>>(bool&)
,它的行为类似于 std::num_get::get
,在提取 bool
时,如果无法提取到 bool
,它会赋值为 false
。这就是为什么你看到输出为 0
。
来自 cppreference 的相关部分(强调是我的):
> 如果目标序列是唯一匹配的,v
就会被设置为相应的 bool
值。否则 false
会被存储在 v
中,并将 std::ios_base::failbit
赋给 err
。如果在输入结束之前找不到唯一匹配 (in == end)
,则会执行 err |= std::ios_base::eofbit
。
为了获得上下文,请查看链接,引用所有内容并详细说明所有步骤对于这个问题的范围来说可能过于繁琐。
总的来说,没有理由期望你的代码的两个版本会产生相同的结果。赋值一个字符串文字和从流中提取输入是完全不同的情况。
英文:
As mentioned in a comment you are comparing apples with oranges. The two versions of your code do something totally different. While the first is about array to pointer decay and pointer to bool conversion, the other is not about that at all. The second is about formatted extraction from input streams.
Here
bool x="ahmed";
The const char[6]
decays to a const char*
and is subsequently converted to bool
. Null pointers convert to false
while others convert to true
. Hence you get 1
as output.
Here
bool x;
cin>>x;
Things are more involved. You are calling std::istream::operator>>(bool&)
which acts like std::num_get::get
, which in case of extracting a bool
assigns false
when no bool
can be extracted. Thats why you see 0
as output.
The relevant part from cppreference (emphasize mine):
> If the target sequence is uniquely matched, v
is set to the corresponding bool
value. Otherwise false
is stored in v
and std::ios_base::failbit
is assigned to err
. If unique match could not be found before the input ended (in == end)
, err |= std::ios_base::eofbit
is executed.
For context, please follow the links, quoting it all and walking trough all the steps in details, would be too much for the scope of this question.
The bottomline is that there is no reason to expect the two versions of your code to yield the same result. Assigning a string literal and extracting input from a stream is completely different stories.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论