char vs. string

In the past I have programmed in BASIC but am trying to learn some c++.
So I might write a program in BASIC and then translate it to c++.
But BASIC and C++ seem to deal with strings differently?

This program extracts strings between a comma/space and a semicolon.
The BASIC version works but there seems to be a problem with the string arrays in the C++ version?

BASIC VERSION:
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
dim as string s1      'main string
dim as string s2(10)  'save extracted strings
dim as integer count  'number of saved strings
dim as string temp    'temporary string
dim as integer flag     'start of reading string

s1 = "Hello, my name is, Nathan; It's, a pleasure, to meet you;"

for i as integer = 0 to len(s1)-1
    
    if s1[i] = asc(",") and flag = 1 then
        temp = ""
        flag = 0
    else
        flag = 1
    end if
    if flag = 1 then
        if s1[i]<> asc(";") then
            temp = temp + chr(s1[i])
        else
            print temp
            s2(count) = temp
            count = count + 1
            temp = ""
            flag = 0
        end if
    end if
    
                
next i

sleep 


And its conversion to C++ which crashes when I uncomment lines 30 and 31
//s2[count] = temp;
//count++;

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 <string>

using namespace std;

int main()
{
    string s1 = "Hello, my name is, Nathan; It's, a pleasure, to meet you;";
    string temp;
    string s2[10];
    int count;
    int flag;
    for (int i = 0; i < s1.size();i++)
    {
        if (s1[i] == ',' && flag == 1)
        {
            temp = "";
            flag = 0;
        }
        else{
            flag = 1;
        }

        if (flag == 1)
        {
            if (s1[i] != ';')
                temp = temp + s1[i];
            else{
                cout << temp << endl;
                //s2[count] = temp;
                //count++;
                temp = "";
                flag = 0;
            }
        }

    }

    return 0;
}
Last edited on
This has nothing to do with strings (well, not directly).
Initialise your variables!

int count;

because you haven't done this here, the value of count will be utter rubbish.
Last edited on
@mutexe,
Thank you that fixed it. A bad habit due to BASIC giving an integer a default value of zero.
Topic archived. No new replies allowed.