Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding a C++ program [ Bjarne Stroustrup's book ]

i need your precious help for a small question! I'm reading the Bjarne Stroustrup's book and i found this exemple:

int main()
{
   string previous = " ";
   string current;

   while (cin >> current) {                                    
      if(previous == current)
        cout << "repeated word: " << current << '\n';
      previous = current;
   }                                                            
   return 0;
}

My question is: What does string previous = " "; do?

It initializes previous to the character space (like when you press space). But I thought in C++ it doesn't read it, something about the compiler skipping over whitespace. Why initialize it to that then?

I have tried to write like that: string previous; and the program still work properly... so? What is the differnece? Please enlighten me x)

like image 992
RavenJe Avatar asked Jan 07 '23 07:01

RavenJe


1 Answers

You seam to be confused on what it means in C++ to ignore whitespace. In C++

std::string the_string = something;

is treated the same as

std::string      the_string=something          ;

No when you have a string literal the whitespace in the literal is not ignored as it is part of the charcters of the string. So

std::string foo = " ";

Creates a string with one space where as

std::string foo = "    ";

Creates a string with 4 spaces in it.

like image 106
NathanOliver Avatar answered Jan 18 '23 17:01

NathanOliver