C++ string and char* manipulation acting weird

136 views Asked by At

I have no idea where this code is flawed - mostly because it works fine when I run the .exe under Win7 (compiled with MSVS2010), but it does not work under Ubuntu (compiled with g++)

Here are the problematic segments:

char * context = nullptr;
ifstream input("file.txt");
string line;
while(getline(input, line)) {
    char * line1 = new char[line.size() + 1];
    copy(line.begin(), line.end(), line1);
    line1[line.size()] = '\0';

    char * token = strtok_r(line1, " ", &context);
    if(labela(token))
        cout << "yes";
    else
        cout << "no";
    // ...
    token = (nullptr, " ", &context);
}
// ...

this is the labela(...)

bool labela(char * c) {
    if(c == nullptr)
        return false;
    int i = 0;
    while(c[i] != '\0')
        ++i;
    if(c[--i] == ':')
        return true;
    return false;
}

Whats up with this? I have no idea why it sometimes recognizes a label, and sometimes not.

These are line examples in which it should recognize a label:

label: rest of the line

or

label:
next line

1

There are 1 answers

0
Deqing On

Sometimes it is better to use C++'s own string functions rather than C string functions.

To get the first word of a string, you can simply use substr():

  char* context = 0;
  ifstream input("file.txt");
  string line;
  while(getline(input,line)) {
    //  char* line1 = new char[line.size()+1];
    //  copy(line.begin(),line.end(),line1);
    //  line1[line.size()] = '\0';

    //  char* token = strtok_r(line1, " ", &context);
    string token = line.substr(0, line.find(" "));
    if(labela(token))
        cout << "yes";
    else
        cout << "no";
    ...

You can still use labela():

bool labela(string c) {
    if (c.empty())
        return false;
    ...