繁体   English   中英

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

[英]Does std::cout affect the result of compilation?

我正在使用 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;
    }
}

如果我运行这段代码,我会得到一个运行时错误(见这里)。

但是,如果我取消注释“blah”行,我将获得“成功”并打印“blah h blah m blah n blah i blah r”(请参阅此处)。

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

谁能帮我解决这个问题? 谢谢!

cout正在使用缓冲区。 在该缓冲区被刷新之前,“输出”保留在缓冲区中 - 内存

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM