【问题标题】:C++ string and char* manipulation acting weirdC++ 字符串和 char* 操作行为怪异
【发布时间】:2015-06-08 20:54:55
【问题描述】:

我不知道这段代码的缺陷在哪里——主要是因为当我在 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()] = '\0';

    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] != '\0')
        ++i;
    if(c[--i] == ':')
        return true;
    return false;
}

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

这些是应该识别标签的行示例:

标签:行的其余部分

标签:
下一行

【问题讨论】:

  • 如果 c[0] 为零,则您的条件不好。
  • token = (NULL," ",&amp;context); 这是实际代码吗? labela 函数的真正目标是什么?不管它是什么,我敢打赌它不需要经历那种令人头疼的循环。编辑:您所做的只是搜索: 字符?
  • en.cppreference.com/w/cpp/string/byte/strchr 另外,如果你没有在循环中释放内存,那么每次迭代都会泄漏内存。
  • 你到底想在这里做什么?

标签: c++ string ubuntu char g++


【解决方案1】:

有时使用 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()] = '\0';

    //  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;
    ...

【讨论】:

    猜你喜欢
    • 2017-01-11
    • 1970-01-01
    • 1970-01-01
    • 2017-04-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-25
    相关资源
    最近更新 更多