0

How to replace all space characters (' ') with commas (,) in a string in c++.

This is what I tried.

#include <iostream>
#include <algorithm>

using namespace std;

int main()
{
    string a;
    cin >> a;
    replace(a.begin(), a.end(), ' ', ',');
    cout << a << endl;
}

But when I enter something like this for example (stack overflow) it only returns (stack) for some reason.

Can someone correct the code please?

user207421
  • 305,947
  • 44
  • 307
  • 483
LuckyFire
  • 41
  • 7
  • 3
    Your replacement code is correct, but cin stops reading at the first white space. Try using getline instead. – Werner Henze Feb 26 '20 at 22:07
  • 1
    TL;DR of the dupe: Replace `cin >> a;` with `getline(cin, a)` so that you read in the full string. (cin stops at white space) – NathanOliver Feb 26 '20 at 22:07
  • @NathanOliver Thanks, why don't you post this as an answer also. – LuckyFire Feb 26 '20 at 22:10
  • We don't need to repeat the same answer all over the place. This question has been asked and answered before so it's policy to close it as a duplicate. – NathanOliver Feb 26 '20 at 22:14

0 Answers0