Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/rest/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ c++;打印字符串的内容_C++_String - Fatal编程技术网

C++ c++;打印字符串的内容

C++ c++;打印字符串的内容,c++,string,C++,String,有人能解释一下为什么我不能使用cout=0打印下面代码中的字符串hexaDeciNum;j——){ //cout您试图访问超出范围的字符串索引。 如果不打印solution(word)而尝试打印solution(word).size()则会得到“0”,因为字符串仍然为空 尝试hexaDeciNum。初始化数组时向后推(x)。这将把新字符放在当前字符串的末尾。您将始终返回空字符串。您的hexaDeciNum的长度始终为0。您需要在粘贴符号时更改其大小。hexaDeciNum[i]=temp+48;

有人能解释一下为什么我不能使用
cout=0打印下面代码中的字符串
hexaDeciNum
;j——){
//cout您试图访问超出范围的字符串索引。 如果不打印
solution(word)
而尝试打印
solution(word).size()
则会得到“0”,因为字符串仍然为空


尝试
hexaDeciNum。初始化数组时向后推(x)
。这将把新字符放在当前字符串的末尾。

您将始终返回空字符串。您的
hexaDeciNum
的长度始终为0。您需要在粘贴符号时更改其大小。
hexaDeciNum[i]=temp+48;
更改不属于此字符串的内存值。
push_back()
将调整字符串大小并在字符串末尾添加符号。更改部分代码:

// check if temp < 10
if(temp < 10)
{
    hexaDeciNum.push_back(temp + 48);
    i++;
}
else
{
    hexaDeciNum.push_back(temp + 55);
    i++;
}
//检查温度是否<10
如果(温度<10)
{
十六进制推回(温度+48);
i++;
}
其他的
{
十六进制推回(温度+55);
i++;
}

您的代码中存在大量错误。首先,您在
hexaDeciNum
上使用的下标运算符索引超出了范围。此外,您可能打算允许
hexaDeciNum
也包含字符9-2。如果添加这些检查,您应该会看到输出已更正


这里的最佳解决方案是使用标准内置功能来解决此问题:

string solution(string &S){
    const auto n = stoi(S);
    const auto hexaDeciNum = static_cast<ostringstream&>(ostringstream() << hex << uppercase << n).str();

    return all_of(cbegin(hexaDeciNum), cend(hexaDeciNum), [](const unsigned char i){ return isxdigit(i); }) ? hexaDeciNum : "ERROR"s;
}
string解决方案(string&S){
常数自动n=stoi(S);

const auto hexaDeciNum=static_cast(ostringstream()为什么您认为必须这样做?尝试时会发生什么?确实,您不需要显式循环来打印字符串。除了输出之外,这里还有很多问题。值得注意的是,您不应该在不分配字符串的情况下使用方括号运算符。您会得到什么错误/错误的输出?避免使用
temp+48
中的幻数,和(错误,因为我假设您使用ASCII,其中
'A'
65
temp+55
temp+'0'
temp+'A'
更清晰(但也不是可移植的
'A'
-
'Z'
不保证是连续的)。您可以使用可移植的
“0123456789ABCDEF”[temp]
取而代之。谢谢你的帮助。我想知道如果字符串为空,我怎么能打印for循环中的字符?谢谢(int j=I-1;j>=0;j--){cout@arcoxiatom您正在写入字符串内存之外的内存,它不属于
hexaDeciNum
。您更改了不属于
hexaDeciNum
的内存,这很糟糕。您可以更改其他重要数据。因此您需要使用
push_back()
以正确的方式更改其值。还有其他一些方法。
string solution(string &S){
    const auto n = stoi(S);
    const auto hexaDeciNum = static_cast<ostringstream&>(ostringstream() << hex << uppercase << n).str();

    return all_of(cbegin(hexaDeciNum), cend(hexaDeciNum), [](const unsigned char i){ return isxdigit(i); }) ? hexaDeciNum : "ERROR"s;
}