简体   繁体   中英

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.

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 ).

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.

Can anyone help me with this problem? Thanks!

cout is using a buffer. Until that buffer is flushed the "output" remains in the buffer - memory

But the while loop 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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