gre*_*rep 1 c++ string pointers iterator
当我将Iterator附加到字符串时,我遇到了一些意外的字符串行为.基本上,我有一个文件,读取的内容如下:
int x := 10;
print x;
Run Code Online (Sandbox Code Playgroud)
我有一个字符串已经包含这个文件的内容,我正在迭代它,只是现在删除空格.
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;
}
Run Code Online (Sandbox Code Playgroud)
在循环结束时,我希望CurToken是一个字符串,只包含删除了所有空格的字符.相反,我得到以下内容:
int x := 1 + 2;
print x;
nt x := 1 + 2;
print x;
t x := 1 + 2;
print x;
Run Code Online (Sandbox Code Playgroud)
...
rint x;
int x;
nt x;
t x;
x;
;
Run Code Online (Sandbox Code Playgroud)
我假设问题是取消引用指针,如果是,我怎么能追加当前指针位置的字符?如果我不解除它,我最终会invalid conversion from ‘char’ to ‘const char*’
注意: is_whitespace()我已经测试过,并按预期工作.因此可以排除这可能是一个问题.
CurToken.append(&*Pointer);
Run Code Online (Sandbox Code Playgroud)
假设Pointer是一个指针,那相当于
CurToken.append(Pointer);
Run Code Online (Sandbox Code Playgroud)
并将字符串的整个尾部附加到CurToken(假设它指向一个C风格的以零结尾的字符串;如果没有终结符则可能发生任何事情).看起来你只想附加当前字符:
CurToken.append(*Pointer);
Run Code Online (Sandbox Code Playgroud)
更新:你说的Pointer是std::string::iterator.在这种情况下,&*Pointer仍然是指向角色的指针; 并append仍然将其解释为指向C风格字符串的指针.由于字符串中的字符不一定被终止(虽然在实践中它们几乎肯定会,特别是在C++ 11库中),但是你有未定义的行为.
| 归档时间: |
|
| 查看次数: |
2365 次 |
| 最近记录: |