处理字符串时出现超级奇怪的错误
Super weird error when handling strings
我正在尝试创建一个将二进制数(字符串)转换为十进制数(整数)的函数。下面代码的奇怪之处在于,当行"//cout <<索引<<endl;"没有被注释掉时,它可以工作!为什么是D:?
注释掉时的输出:
1651929379
激活时的输出:
7 192 程序以退出代码结束:0
这是整个程序:
//
// testish.cpp
// Egetskojs
//
// Created by Axel Kennedal on 2014-02-13.
// Copyright (c) 2014 Axel Kennedal. All rights reserved.
//
#include <iostream>
#include <string>
#include <cmath>
using namespace std;
int BinaryToDecimal(string & binaryString);
int main(){
string binary = "11000000";
int decimal = BinaryToDecimal(binary);
cout << decimal << endl;
return 0;
}
int BinaryToDecimal(string & binaryString){
int solution;
if (binaryString == "0") solution = 0;
if (binaryString == "1") solution = 1;
int index = binaryString.length() - 1; //The index of the last (rightmost) bit in the string
//cout << index << endl;
int currentBit = 0; //The exponent to be used when calculating the value of a bit
for (; index >= 0; index--) {
if (binaryString.at(index) == '1') {
solution += pow(2, currentBit);
}
//Else: nothing happens
currentBit++;
}
//Done!
return solution;
}
你在
BinaryToDecimal
中有未定义的行为,因为变量solution
可能在未初始化的情况下使用。
未初始化的局部变量将具有不确定的值(即它们的值似乎是随机的)。
正如 Joachim 所说,您的解决方案变量是未初始化的,因此当字符串既不是"0"也不是"1"时,您可能会在 += 操作中出现奇怪的行为(例如整数溢出)。我猜它在输出处于活动状态时工作的事实是由于输出指令的一些奇怪的副作用导致某些寄存器包含 0,并且该寄存器是 solution
值的来源。了解编译器设置的内容并查看这部分代码的汇编程序代码可能会有所启发。
您可以替换:
int BinaryToDecimal(string & binaryString){
int solution;
if (binaryString == "0") solution = 0;
if (binaryString == "1") solution = 1;
...
跟:
int BinaryToDecimal(string & binaryString){
int solution = 0;
...
由于您所做的特殊情况处理由您的循环优雅地处理。
相关文章:
- 由cin中的字符串中未捕获空白引起的分割错误
- 将 GetLastError() 转换为带有错误字符串的异常
- Rapidjson 解析错误:字符串 (207) 中的编码无效
- 尝试对字符串[数组]>>cin 并出现错误(" "字符串下标超出范围")
- 如何检索 DirectX 9 的错误字符串
- 从 C++ => C 包装的 API(多线程)传输错误字符串
- 错误字符串下标超出c++范围
- 获取Openssl证书错误中的错误字符串
- 作为宏参数的安装类型返回错误:字符串常量之前的预期非限定 id
- 语法错误字符串方法C++
- 对于静态错误字符串,哪个的内存/性能效率更高,或者有替代方案
- 使用 strtok() 的错误字符串比较
- C++ 中的运行时错误字符串声明
- 我收到错误:字符串声明上的 C2501
- GCC:为什么一行代码中的错误(字符串和NULL的比较)会导致一长串错误消息
- 错误C2059:语法错误:'字符串'
- 致命错误:字符串:没有这样的文件或目录编译终止
- C++错误:字符串下标超出范围
- 这里面有什么错误?字符串赋值
- 是否有标准的方法来查询EGL错误字符串