c++字符串和char*操作行为怪异

C++ string and char* manipulation acting weird

本文关键字:操作 字符串 char c++      更新时间:2023-10-16

我不知道这段代码在哪里有缺陷-主要是因为当我在Win7(用MSVS2010编译)下运行。exe时它工作得很好,但它在Ubuntu(用g++编译)下不起作用

以下是有问题的片段:

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()] = '';
    char * token = strtok_r(line1, " ", &context);
    if(labela(token))
        cout << "yes";
    else
        cout << "no";
    // ...
    token = (nullptr, " ", &context);
}
// ...

这是标签(…)

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

这是怎么回事?我不知道为什么它有时能识别标签,有时不能。

以下是它应该识别标签的行示例:

label: 剩余行

label:
下一行

有时使用c++自己的字符串函数比使用C的字符串函数更好。

要获取字符串的第一个单词,您可以简单地使用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()] = '';
    //  char* token = strtok_r(line1, " ", &context);
    string token = line.substr(0, line.find(" "));
    if(labela(token))
        cout << "yes";
    else
        cout << "no";
    ...

您仍然可以使用labela():

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