std::cout会影响编译的结果吗

Does std::cout affect the result of compilation?

本文关键字:结果 编译 影响 cout std      更新时间:2023-10-16

我使用C++接收一个包含一些单词的字符串,这些单词由任意数量的空格分隔,并打印出每个单词的第一个字母。

这是我的代码:

#include <iostream>
#include <string>
using namespace std;
int main() {
string str = "hi     my name  is      rex";
int i = 0;
int len = str.length();
while (i < len) {
// cout << " blah ";        // <--- Note this line
cout << str[i];
while (str[i] != ' ') ++i;
while (str[i] == ' ') ++i;
}
}

如果我运行这段代码,我将得到一个运行时错误(请参阅此处)。

然而,如果我不评论"废话"行,我将获得"成功",并打印出"废话"(见此处)。

我知道我可能应该检查I<len在这两个嵌套的while循环中,但我想知道的是,为什么打印"blah"行会对编译结果产生如此大的影响。

有人能帮我解决这个问题吗?谢谢

cout正在使用缓冲区。在该缓冲区被刷新之前,"输出"将保留在缓冲存储器中

但是当到达字符串的末尾时while循环while (str[i] != ' ') ++i;继续进行。在线IDE给程序一些时间,然后放弃或出现分段故障