将带有转义序列的 std::string 转换为 ascii 值
Converting std::string with escape sequence to ascii values
我有一个 std::string,我想对其进行迭代并基本上变成一个代表每个字符的 ascii 值的 int 值流。
我的问题是转义字符。比如 "\n".
std::string str = "hello\nhello";
for (char c : str) {
int asciiVal = static_cast<int>(c);
// now do something with val. but what about the escape sequence?
}
问题在于此代码只是将“\n”视为两个单独的字符。
更新:
这是一个真正的问题。
是的,它不会发生在普通的 c++ 代码中,但会发生在包含 C/C++ 摘录的 .lex 文件中。
这是真正的代码和输出:
代码:.lex 文件
char *c = yytext;
c[yyleng-1] = '[=12=]';
c++;
std::string str = c;
cout << "MY STRING: '" << str << "'" << endl;
for (char c : str) {
int val = static_cast<int>(c);
std::cout << to_string(val) << std::endl;
}
输出:
MY STRING: '\n'
92
110
不,"\n"
将被视为单个 char
(0x0a)。如果你想要两个 char
s 使用 "\n"
.
the problem is that this code just treat "\n" as two separate characters.
any help?
不,不是。转义字符与常规字符一样存储 - 因此 \n
将像 a
或 b
一样处理。
http://www.cplusplus.com/doc/tutorial/ntcs/
您可以通过打印 asciiVal
来验证。在您的情况下,输出为:
104 // h
101 // e
108 // l
108 // l
111 // o
10 // \n
104 // h
101 // e
108 // l
108 // l
111 // o
在您修改过的问题中,很明显您的输入字符串 实际上包含两个单独的字符。
(原版问题不是这样的)
因此您必须自己解决它们,方法是扫描 '\'
字符,然后(取决于下一个字符是什么),将其替换为所需的 meta-character.
更改您需要更改的任何设置以使您的输入字符串 实际上 包含 '\n'
字符,而不是反斜杠后跟一个字符会容易得多'n'
.
我有一个 std::string,我想对其进行迭代并基本上变成一个代表每个字符的 ascii 值的 int 值流。
我的问题是转义字符。比如 "\n".
std::string str = "hello\nhello";
for (char c : str) {
int asciiVal = static_cast<int>(c);
// now do something with val. but what about the escape sequence?
}
问题在于此代码只是将“\n”视为两个单独的字符。
更新:
这是一个真正的问题。 是的,它不会发生在普通的 c++ 代码中,但会发生在包含 C/C++ 摘录的 .lex 文件中。 这是真正的代码和输出:
代码:.lex 文件
char *c = yytext;
c[yyleng-1] = '[=12=]';
c++;
std::string str = c;
cout << "MY STRING: '" << str << "'" << endl;
for (char c : str) {
int val = static_cast<int>(c);
std::cout << to_string(val) << std::endl;
}
输出:
MY STRING: '\n'
92
110
不,"\n"
将被视为单个 char
(0x0a)。如果你想要两个 char
s 使用 "\n"
.
the problem is that this code just treat "\n" as two separate characters.
any help?
不,不是。转义字符与常规字符一样存储 - 因此 \n
将像 a
或 b
一样处理。
http://www.cplusplus.com/doc/tutorial/ntcs/
您可以通过打印 asciiVal
来验证。在您的情况下,输出为:
104 // h
101 // e
108 // l
108 // l
111 // o
10 // \n
104 // h
101 // e
108 // l
108 // l
111 // o
在您修改过的问题中,很明显您的输入字符串 实际上包含两个单独的字符。
(原版问题不是这样的)
因此您必须自己解决它们,方法是扫描 '\'
字符,然后(取决于下一个字符是什么),将其替换为所需的 meta-character.
更改您需要更改的任何设置以使您的输入字符串 实际上 包含 '\n'
字符,而不是反斜杠后跟一个字符会容易得多'n'
.