gpt4 book ai didi

C++追加字符串指针

转载 作者:太空宇宙 更新时间:2023-11-03 10:33:17 25 4
gpt4 key购买 nike

当我将 Iterator 附加到字符串时,我遇到了一些意外的字符串行为。基本上,我有一个文件可以读取以下内容:

int x := 10;
print x;

我已经有一个包含此文件内容的字符串,我正在遍历它并立即简单地删除空格。

void Lexer::parse()
{
Pointer = Filestring.begin(); // both private members
while(Pointer < Filestring.end())
{
if(is_whitespace(0)) // 0 indicates current Pointer position
{
advance(Pointer, 1);
continue;
}

CurToken.append(&*Pointer); // CurToken is private member string
advance(Pointer, 1);
}

cout << CurToken << endl;
}

在循环结束时,我希望 CurToken 是一个只包含删除了所有空格的字符的字符串。相反,我得到如下内容:

int x := 1 + 2;
print x;



nt x := 1 + 2;
print x;



t x := 1 + 2;
print x;

...

rint x;



int x;



nt x;



t x;



x;



;

我假设问题是取消对指针的引用,如果是这样,我如何附加当前指针位置的字符?如果我不取消引用它,我最终会得到 invalid conversion from ‘char’ to ‘const char*’

注意: is_whitespace() 我已经测试过,并且按预期工作。这样就可以排除可能的问题。

最佳答案

CurToken.append(&*Pointer);

假设 Pointer 是一个指针,那等同于

CurToken.append(Pointer);

并将字符串的整个尾部附加到 CurToken 上(假设它指向 C 风格的零终止字符串;如果没有终止符,则可能发生任何事情)。看起来您只想附加当前字符:

CurToken.append(*Pointer);

更新:你说 Pointerstd::string::iterator。在那种情况下,&*Pointer 仍然是指向该字符的指针; append 仍会将其解释为指向 C 风格字符串的指针。由于字符串中的字符不一定终止(尽管在实践中它们几乎肯定会终止,尤其是在 C++11 库中),因此您会遇到未定义的行为。

关于C++追加字符串指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10230738/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com