gpt4 book ai didi

c++ - 了解 C++ 程序 [ Bjarne Stroustrup 的书 ]

转载 作者:可可西里 更新时间:2023-11-01 13:51:52 24 4
gpt4 key购买 nike

我需要你宝贵的帮助来解决一个小问题!我正在阅读 Bjarne Stroustrup 的书,我发现了这个例子:

int main()
{
string previous = " ";
string current;

while (cin >> current) {
if(previous == current)
cout << "repeated word: " << current << '\n';
previous = current;
}
return 0;
}

我的问题是:string previous = ""; 有什么作用?

它将 previous 初始化为字符空格 (就像您按空格键时一样)。但我认为在 C++ 中它不会读取它,这是关于编译器跳过空格的事情。为什么要将它初始化为那个?

我试过这样写:string previous; 并且该程序仍然可以正常工作...所以?有什么区别?请赐教x)

最佳答案

您可能对 C++ 中忽略空格的含义感到困惑。在 C++ 中

std::string the_string = something;

被视为相同

std::string      the_string=something          ;

当你有 string literal 时不文字中的空格不会被忽略,因为它是字符串字符的一部分。所以

std::string foo = " ";

创建一个包含一个空格的字符串,其中 as

std::string foo = "    ";

创建一个包含 4 个空格的字符串。

关于c++ - 了解 C++ 程序 [ Bjarne Stroustrup 的书 ],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33353760/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com