2013-03-31 51 views
-2

im在字符數組下面存儲一個值,比如6。 我想爲相同的值6傳遞給integet陣列而只是此代碼dosent工作:Turbo C++ charecter數組到int數組

char a[3]; 
gets(a);    (for ex: value of a i.e a[0] is 6) 
int b[3]; 
for(int i=0;i<strlen(a);i++) 
b[i]=a[i]; 
cout<<b;    (it returns 54 nd not 6) 

上述代碼存儲的6整數值在它。它不直接存儲6。 我想存儲相同的否6而不是整數值(即54)。 有什麼想法?

在此先感謝

+0

的Visual Studio Express是一個免費的downl爲善的緣故誰還會使用Turbo C++?這顯然迫使你編寫C代碼而不是C++代碼。它不支持'fgets'嗎? –

回答

2

您正在存儲字符代碼,而不是整數。如果在標準輸入上鍵入1並將其存儲在char中,將存儲的是1的ASCII碼,而不是整數值1

因此,如果您分配給b[i],你應該做的:

b[i] = a[i] - '0'; // Of course, this will make sense only as long 
        // as you provide digits in input. 

而且,這樣做:

cout << b; 

將打印b數組的地址,而不是它的內容。此外,在這裏使用strlen()並不是一個好主意,因爲您的數組a不是空終止的。

讓一旁如何類型不安全的,這是,這裏的因素是什麼,你可能打算做的事:

#include <iostream> 
#include <cstring> 

using std::cout; 

int main() 
{ 
    char a[3] = { 0, 0, 0 }; 
    gets(a); 

    int b[3]; 
    for(unsigned int i = 0; i < std::min(strlen(a), 3u); i++) 
    { 
     b[i] = a[i] - '0'; 
    //    ^^^^^ 
     cout << b[i]; 
    } 
} 

這裏是你會怎麼做上面的C++ 11:

#include <iostream> 
#include <string> 
#include <vector> 

int main() 
{ 
    std::string a; 
    getline(std::cin, a); 

    std::vector<int> b; 
    for (char c : a) { if (std::isdigit(c)) b.push_back(c - '0'); } 

    for (int x : b) { std::cout << x << " "; } 
} 

這裏是上述功能的修改應該針對C++ 03以及工作:

#include <iostream> 
#include <string> 
#include <vector> 

int main() 
{ 
    std::string a; 
    getline(std::cin, a); 

    std::vector<int> b; 
    for (std::string::iterator i = a.begin(); i != a.end(); i++) 
    { 
     if (std::isdigit(*i)) b.push_back(*i - '0'); 
    } 

    for (std::vector<int>::iterator i = b.begin(); i != b.end(); i++) 
    { 
     std::cout << *i << " "; 
    } 
} 
+0

其實我試着用下面的代碼使用單個字符'6'。從整數數組返回的值是6-48-65。你能解釋一下嗎?我只想在b [0]下的值6而不是它的ASCII值。當我訪問b [0]時,它顯示6,但爲什麼它存儲-48和-65?你能解釋一下嗎? – user2229186

+0

@ user2229186:您使用了哪種解決方案?第一個還是第二個? –

+0

我曾經使用過第一個。 – user2229186