简体   繁体   English

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

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

I am using C++ to take in a string with some words, which are separated by any number of spaces, and print out the first letter of each word.我正在使用 C++ 接收一个包含一些单词的字符串,这些单词由任意数量的空格分隔,并打印出每个单词的第一个字母。

Here is my code:这是我的代码:

#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;
    }
}

If I run this piece of code, I will get a runtime error ( see here ).如果我运行这段代码,我会得到一个运行时错误(见这里)。

However, if I un-comment the "blah" line, I will get "success" and " blah h blah m blah n blah i blah r" is printed ( see here ).但是,如果我取消注释“blah”行,我将获得“成功”并打印“blah h blah m blah n blah i blah r”(请参阅此处)。

I know I probably should check i < len inside those two nested while loops, but what I'm wondering is why does printing the "blah" line make so much difference to the result of compilation.我知道我可能应该在这两个嵌套的 while 循环中检查 i < len,但我想知道为什么打印“blah”行对编译结果有如此大的影响。

Can anyone help me with this problem?谁能帮我解决这个问题? Thanks!谢谢!

cout is using a buffer. cout正在使用缓冲区。 Until that buffer is flushed the "output" remains in the buffer - memory在该缓冲区被刷新之前,“输出”保留在缓冲区中 - 内存

But the while loop while (str[i] != ' ') ++i;但是 while 循环while (str[i] != ' ') ++i; keeps going when the end of string is reached.到达字符串末尾时继续前进。 The online IDE gives the program some time then gives up or segmentation fault occurs在线IDE给程序一些时间然后放弃或出现分段错误

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

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