-2

I can split a given text into a list, but it doesn't work if I want to split a string given by the user.

void removeDupWord(string str)
{
    string word = "";
    for (auto x : str)
    {
        if (x == ' ')
        {
            cout << word << endl;
            word = "";
        }
        else
        {
            word = word + x;
        }
    }
    cout << word << endl;
}

int main()
{
    string ss;
    cin >> ss;
    ss = "split this";
    removeDupWord(ss);
}

1 Answers1

1

Use std::getline instead of std::cin. With std::cin the input after whitespace will be discarded.

int main()
{
    string ss;
    std::getline(std::cin, ss);
    //ss = "split this";
    removeDupWord(ss);
}

Also, you should use C++ standard algorithm for such trivial task

void removeDupWord(const std::string& str)
                 // ^^^^^^^^^^^^^^^^^ Noice this change
{
    std::stringstream ss(str);
   
    std::copy(std::istream_iterator<std::string>{ss}, 
              std::istream_iterator<std::string>{},
              std::ostream_iterator<std::string>(std::cout, "\n"));
}

Demo Here

P0W
  • 46,614
  • 9
  • 72
  • 119
  • @P0W Why are you writing "std::istream_iterator{}" as 2nd parameter to ````std::copy````? A simple "{}" would be sufficient. Like ````std::copy(std::istream_iterator(ss), {}, std::ostream_iterator(std::cout, "\n"));```` – A M Oct 05 '20 at 15:15