我试图理解字符串在C++中是如何工作的,因为在遇到意外行为后我真的很困惑.
考虑一个字符串,我append()使用[]运算符插入一个字符(不使用):
string str;
str[0] = 'a';
Run Code Online (Sandbox Code Playgroud)
让我们打印字符串:
cout << "str:" << str << endl;
Run Code Online (Sandbox Code Playgroud)
我得到NULL作为输出:
str:
Run Code Online (Sandbox Code Playgroud)
好的,让我们尝试打印字符串中唯一的字符:
cout << "str[0]:" << str[0] << endl;
Run Code Online (Sandbox Code Playgroud)
输出:
str[0]:a
Run Code Online (Sandbox Code Playgroud)
Q1.那里发生了什么?为什么a不在第一种情况下打印?
现在,我做了一些应该抛出编译错误的东西,但它没有,我的问题又是,为什么.
str = 'ABC';
Run Code Online (Sandbox Code Playgroud)
Q2.那不是一个不正确的语义,即将字符(实际上不是字符,但实际上是单引号中的字符串)分配给字符串?
现在,更糟糕的是,当我打印字符串时,它总是打印最后一个字符,即C(我期待第一个字符,即A):
cout << "str:" << str << endl;
Run Code Online (Sandbox Code Playgroud)
输出:
str:C
Run Code Online (Sandbox Code Playgroud)
Q3.为什么打印最后一个字符,而不是第一个?
我有以下处理双打的代码:
static bool
double_param(const char ** p, double * ptr_val)
{
char *end;
errno = 0;
double v = strtod(*p, &end);
if (*p == end || errno) return false;
*p = end;
*ptr_val = v;
return true;
}
Run Code Online (Sandbox Code Playgroud)
此代码用于检查传递的双参数是否无效,如下所示:
if (!double_param(&p, &b1)) //p is pointer and b1 is parameter.
//throw error;
Run Code Online (Sandbox Code Playgroud)
而且,我需要编写一个等效的代码来处理 3 个字符长的字符串。我自己得到了这个:
static bool
string_param(const char ** p, const string * ptr_val)
{
char *end;
errno = 0;
int v = strtol(*p, &end, 10);
if (*p == end …Run Code Online (Sandbox Code Playgroud)