我需要您的宝贵帮助来解决一个小问题! 我正在阅读 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 = " ";
创建一个带有一个空格的字符串,其中
std::string foo = " ";
创建一个包含 4 个空格的字符串。
关于c++ - 理解 C++ 程序 [Bjarne Stroustrup 的书],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33353760/
欢迎光临 OStack程序员社区-中国程序员成长平台 (http://ostack.cn/) | Powered by Discuz! X3.4 |