Home > Software design >  When I run my code it display random symbols at the end
When I run my code it display random symbols at the end

Time:01-27

I am separating a string into words and when I run the source code, it works but at the end it displays random symbols and letter.

#include <iostream>
#include <cstring>
#include <cctype>

using namespace std;


void seperatestring(string str);
 

int main()
{
    string str;
    cout << "Enter a string: ";
    getline(cin, str);
    seperatestring(str);
    return 0;
}

void seperatestring(string str)
{
    string word = "";
    for (int i = 0; i < str[str.size()-1] ; i  )
    {
        if (str[i] == ' ')
        {
            cout << word << endl;
            word = "";
        }
        else {
            word = word   str[i];
        }
    }
    cout << word << endl;
}

This is the source code. The only problem is that at the end of the result there are random symbols and letters. What should I fix in my source code to remove the random symbols at the end?

CodePudding user response:

this looks suspicious:

for (int i = 0; i < str[str.size()-1] ; i  )

Don't you really mean:

for (int i = 0; i < str.size(); i  )
  • Related