Nico van Bentum
Nico van Bentum

Reputation: 347

string replace breaks on space in C++

If I input "we are going to have fun in school" when executing the following code, it seems to break after the first word and only prints "W3". Does anyone know what I did wrong?

#include <iostream>
#include <algorithm>
#include <string>
using namespace std;

int main()
  {
  string s;
  cout << "Invoer: ";
  cin >> s;

  replace( s.begin(), s.end(), 'e', '3' );
  replace( s.begin(), s.end(), 'o', '0' );
  replace( s.begin(), s.end(), 't', '7' );
  replace( s.begin(), s.end(), 'l', '1' );
  transform( s.begin(), s.end(), s.begin(), ::toupper);

  cout << s << endl;

  return 0;
}

Upvotes: 1

Views: 608

Answers (1)

AndyG
AndyG

Reputation: 41092

You need to use getline instead of cin >> s to grab the whole line, otherwise it stops at whitespace:

getline(cin, s);

Live demo

Upvotes: 7

Related Questions