Home > OS >  Displaying the content of a vector
Displaying the content of a vector

Time:01-21

string s="dog cat cat dog"
vector<string>v;
for(int i=0;i<s.length();)
{
    string str;
    while(s[i]!=' ')
    {
        str.push_back(s[i]);
            i  ;
    }
    v.push_back(str);
    i  ;
}
for(auto it=v.begin();it!=v.end();it  )
{
    cout<<*(it)<<" ";
}

I want my output to be like:

dog cat cat dog 

But I am getting some unwanted symbols also in the output and don't know what they mean.

Output:

dog cat cat dog ♫)±*→╒ ‼♥       ♦               dog             ♫)≡ →╒  ►\☻     P☺☻             dog ♫)±*        ♫)±*→╒ ‼♥       ♦               cat             ♫)±*→╒ ‼♥       ♦               cat             ▬)≡3→╒  ≡^☻     Ç[☻             dog ♫)±*→╒ ‼♥    ☺ 8→╒  P☺☻     ♣ ☺♦↔╒ ↨

What are these?

CodePudding user response:

Your original string s, does not end with a ' ' character. This means that your while loop does not terminate at the end of s. You can prevent this by checking i against the length of s.

while(s[i]!=' ' and i < s.length())

CodePudding user response:

This answer already explained the problem with your code.

A much simpler way to split the string on spaces is to use std::istringstream with operator>>, eg:

string s = "dog cat cat dog", str;
vector<string> v;
istringstream iss(s);
while (iss >> str)
{
    v.push_back(str);
}
for(const auto &str_in_v : v)
{
    cout << str_in_v << " ";
}
  •  Tags:  
  • Related