[英]C++ I cannot cout one string while i successfully cout an another string
我有一個很奇怪的問題。 我在做什么是我正在嘗試在代碼末尾將字符串中的8位二進制數轉換為十進制數(也為字符串),但我卻發現了二進制字符串和十進制字符串,但是當我運行時,我只能成功看到二進制字符串而不是十進制字符串...
這是我的代碼:
#include <iostream>
#include <string>
#include <stdlib.h>
using namespace std;
void bintodec(string bin);
int main()
{
string bin="";
bintodec(bin);
return 0;
}
void bintodec(string bin)
{
int temp;
int temp_a;
int temp_b;
string dec;
cout << "Enter the binary number: ";
cin >> bin;
temp = 128*(bin[0]-48) + 64*(bin[1]-48) + 32*(bin[2]-48) + 16*(bin[3]-48) + 8*(bin[4]-48) + 4*(bin[5]-48) + 2*(bin[6]-48) + (bin[7]-48);
temp_a = temp%10;
temp = (temp - temp_a) / 10;
temp_b = temp%10;
temp = (temp - temp_b) / 10;
dec[2]=temp_a+48;
dec[1]=temp_b+48;
dec[0]=temp+48;
dec[3]='\0';
cout << endl << bin << " in decimal is: " << dec << endl;
}
這是運行結果:
輸入二進制數:10101010
十進制的10101010是:
在“是”之后應該是我的十進制數字; 但是什么也沒有。 我嘗試分別退出dec [0] dec [1]和dec [2],但確實有效,但是當我退出整個dec時,每次都失敗了...
誰能告訴我我的問題在哪里? 我認為我的代碼有問題,但我可以弄清楚...
dec
的大小為零。 但是您可以訪問位置0到3處的元素。例如,可以通過使用以下命令創建dec
初始化為適當的大小
string dec(4, ' '); // fill constructor, creates a string consisting of 4 spaces
代替
string dec;
。
@SebastianK已經解決了您的std::string
長度為零的事實。 我想添加以下內容:
dec[2]=temp_a+48;
dec[1]=temp_b+48;
dec[0]=temp+48;
dec[3]='\0';
您可以使用push_back()
成員函數將字符追加到空的std::string
:
dec.push_back(temp + '0');
dec.push_back(temp_b + '0');
dec.push_back(temp_a + '0');
請注意,您不需要NULL終止std::string
並且我使用字符文字'0'
而不是ASCII值48,因為我認為這更清楚。
注意:這只是帶代碼的注釋,而不是實際的答案。
int main()
{
string bin="";
decode(bin);
}
void decode(string bin)
{
}
這將導致在進入“解碼”時創建一個新字符串,並將“ bin”的內容復制到該字符串中。 解碼結束時,對main :: bin所做的任何更改將對main不可見。
您可以避免這種情況-之所以稱為“按值傳遞”,是因為您要傳遞“ bin”而不是“ bin”本身的值-通過使用“按引用傳遞”
void decode(string& bin)
但是在您的代碼中,您實際上似乎根本不需要傳遞“ bin”。 如果解碼后在main中需要“ bin”,則可以考慮返回它:
int main()
{
string bin = decode();
}
string decode()
{
string bin = "";
...
return bin;
}
但是現在,只需從main中刪除bin並將其設置為解碼中的局部變量即可。
void bintodec();
int main()
{
bintodec();
return 0;
}
void bintodec()
{
std::string bin = "";
cout << "Enter the binary number: ";
cin >> bin;
int temp = 128*(bin[0]-48) + 64*(bin[1]-48) + 32*(bin[2]-48) + 16*(bin[3]-48) + 8*(bin[4]-48) + 4*(bin[5]-48) + 2*(bin[6]-48) + (bin[7]-48);
int temp_a = temp%10;
temp = (temp - temp_a) / 10;
int temp_b = temp%10;
temp = (temp - temp_b) / 10;
char dec[4] = "";
dec[2] = temp_a+48;
dec[1] = temp_b+48;
dec[0] = temp+48;
dec[3] = '\0';
cout << endl << bin << " in decimal is: " << dec << endl;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.