String problems

Hi all, I am totally confused about this, and why it doesn't work

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
string sBuf;
    string *sNames;


    fFile.open("id22-names.txt");

    if (!fFile.is_open())
        cout << "Error opening file!" << endl;
    else
        cout << "File opened succesfully :)" << endl;

    getline(fFile, sBuf);    // Puts the contents of fFile in sBuf

    len = 1;
    for (i = 0; i < sBuf.size(); i++)
        if (sBuf.at(i) == ',')
            len++;

    sNames = new string [len];

    try
    {
    for (i = 0, j = 0, n = 0; i < sBuf.size(); i++)
    {
         if (sBuf.at(i) == ',' &&  n != 0)
        {
            j++;
            n = 0;
        }
        else if (!(sBuf.at(i) == ',' || sBuf.at(i) == '"'))
        {
            sNames[j].at(n++) = sBuf.at(i);    // this one generates the exception, why?
            cout << sNames[j];
            getchar();
            fflush(stdin);
        }
        else
            ;

    }

I have no idea why I get an exception with this line sNames[j].at(n++) = sBuf.at(i);.

Any ideas?

thanks
Your problem is here:

sNames[j].at(n++)

Every string in sNames has a length of 0. try sNames[j].push_back(sBuf.at(i)) instead.
Nice, no more exception, but it behaves a bit wierdish. Let me just show you the output, this code:

EDIT: I'm too hasty, so I write before I think, but now I as I was writing I figured out the problem (it was with the 'n' variable). Thanks PanGalactic.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
    for (i = 0, j = 0, n = 0; i < sBuf.size(); i++)
    {
         if (sBuf.at(i) == ',' &&  n != 0)
        {
            j++;
            n = 0;
        }
        else if (!(sBuf.at(i) == ',' || sBuf.at(i) == '"'))
        {
            sNames[j].push_back(sBuf.at(i));
            
        }
        else
            ;
    getchar();
    fflush(stdin);
    cout << sNames[j];

    }


generates:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
M
MA
MAR
MARY
MARYP
MARYPA
MARYPAT
MARYPATR
MARYPATRI
MARYPATRIC
MARYPATRICI
MARYPATRICIA
MARYPATRICIAL
MARYPATRICIALI
MARYPATRICIALIN
MARYPATRICIALIND
MARYPATRICIALINDA


But it should be something more like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
M
MA
MAR
MARY
P
PA
PAT
PATR
PATRI
PATRIC
PATRICI
PATRICIA
L
LI
LIN
LIND
LINDA


I think this bit of code
1
2
3
4
5
         if (sBuf.at(i) == ',' &&  n != 0)
        {
            j++;
            n = 0;
        }

is suppose to jump to the next string as it sees a ','.
Last edited on
Topic archived. No new replies allowed.