Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

When I run my code it display random symbols at the end

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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++)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading