creating a vector of strings

hi all, im trying to write this program that creates a vector of strings where the strings are determined by a letter of the user's choosing.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
#include<iostream>
#include<vector>

using namespace std;

int main()
{
    char cPhrase[]={'I',' ','l','o','v','e',' ','e','a','t','i','n','g',' ',
                    'a','l','l',' ','k','i','n','d','s',' ','o','f',' ','d','e','s','s','e','r','t','s','.','\0'};

    cout << sizeof(cPhrase)<< endl;

    vector<string>cString;

    for(int i=0; i<sizeof(cPhrase);i++){

    string s="";

    for(int j=0; j<1; j++)

    s+=cPhrase[i*1+j];

    cString.push_back(s);

    }

    for(int i=0;i<cString.size();i++)
    {
       cString[i];

       cout << cString[i];

    }




    return 0;
}


where if i choose the letter e the output should be



I love e ating all kinds of de sse rts.



i created the string from a char array but cant think of anything to implement that. plz help.
What does this loop do?

1
2
for(int j=0; j<1; j++)
s+=cPhrase[i*1+j];


And where are you choosing a letter?
Last edited on
What's with the ridiculous initialization of the char array?
char cPhrase[]="I love eating all kinds of desserts.";

Why do you need a vector? There is no need to store the parts before printing them.

i*1+j

That's quite a fancy way of saying i.
Last edited on
it creates the string from the char array
getline() does that

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>
#include <vector>
#include <sstream>
#include <string>

int main()
{
    char cPhrase[]={'I',' ','l','o','v','e',' ','e','a','t','i','n','g',' ',
                    'a','l','l',' ','k','i','n','d','s',' ','o','f',' ','d','e','s','s','e','r','t','s','.','\0'};
    std::istringstream buf(cPhrase);
    std::vector<std::string> cString;
    char delim = 'e';
    for(std::string word; getline(buf, word, delim); )
        cString.push_back(word + delim);

    for(size_t i=0; i<cString.size(); ++i)
       std::cout << '"' << cString[i] << "\" ";
}

(I've added quotation marks to the output to show your word boundaries better, note the caveat with the last word: geline drops the delimiter)
thanks @Cubbi
PS: could also use regex to make it easier to deal with the last word:

1
2
3
4
5
6
7
8
9
10
11
12
#include <iostream>
#include <boost/regex.hpp> // or just <regex>

int main()
{
    char cPhrase[]={'I',' ','l','o','v','e',' ','e','a','t','i','n','g',' ',
                    'a','l','l',' ','k','i','n','d','s',' ','o','f',' ','d','e','s','s','e','r','t','s','.','\0'};
    boost::regex re("[^e]+(e|$)");
    boost::cregex_iterator beg(cPhrase, cPhrase + sizeof cPhrase, re), end;
    for(boost::cregex_iterator i = beg; i != end; ++i)
        std::cout << '"' << *i << "\" ";
}


"I love" " e" "ating all kinds of de" "sse" "rts."

Last edited on
Topic archived. No new replies allowed.