2017-04-11 27 views
-1

d[i] = char(c[i]);需要字符,在C公司國際價值我的電流輸出++

這不是在下面的例子爲我工作。

我需要將我的輸出轉換爲其字符值,但在使用char(int)後,它仍然僅使用int數據類型給出輸出。

#include <bits/stdc++.h> 

using namespace std; 

int main() 
{ 
    string str; 
    cin>>str; 
    int size=str.size(); 
    int len=0; 
    if (size % 2 == 0) 
    { 
     len=size/2; 
    } 
    else 
    { 
     len=(size/2)+1; 
    } 
    int a[len],b[len],c[len],d[len],x,y; 
    int i=0,j=size-1; 
    while(i<len) 
    { 
     x=(int)str[i]; 
     y=(int)str[j]; 
     if (i == j) 
     { 
      a[i]=x; 
     } 
     else 
     { 
      a[i]=x+y; 
     } 
     b[i]=a[i]%26; 
     c[i]=x + b[i]; 
     d[i]=char(c[i]); 
     cout<<"l : "<<d[i]<<endl; 
     i++; 
     j--; 
    } 
    return 0; 
    } 
+0

d [I] = CHAR(C [1]);需要修改這個,所以我的輸出數組d [i]只包含從ASCII int值轉換的字符 – Sagar0807

+0

它不是重複的問題,有人可以給出確切的具體答案,而不是像@Remy Lebeau標記爲重複 – Sagar0807

回答

0

您的代碼失敗,因爲您將值存儲在int[]數組中。 d[i]=char(c[i]);是無用的,因爲你所做的只是將int轉換爲char再次回到int。然後,您輸出的數組值原樣爲int值,而不是將它們轉換回實際的char值。

嘗試更多的東西這樣代替:

#include <vector> 
#include <string> 

using namespace std; 

int main() 
{ 
    string str; 
    cin >> str; 

    int size = str.size(); 
    int len = (size/2) + (size % 2); 

    // VLAs are a non-standard compiler extension are are not portable! 
    // Use new[] or std::vector for portable dynamic arrays... 
    // 
    // int a[len], b[len], c[len]; 
    // char d[len]; 
    // 
    std::vector<int> a(len), b(len), c(len); 
    std::vector<char> d(len); 

    int x, y, i = 0, j = (size-1); 

    while (i < len) 
    { 
     x = (int) str[i]; 
     y = (int) str[j]; 

     if (i == j) 
     { 
      a[i] = x; 
     } 
     else 
     { 
      a[i] = x + y; 
     } 

     b[i] = a[i] % 26; 
     c[i] = x + b[i]; 
     d[i] = (char) c[i]; 

     cout << "l : " << d[i] << endl; 

     ++i; 
     --j; 
    } 

    return 0; 
} 
+0

Fantastic,Thanks for你的意見。缺少一個簡單的步驟 – Sagar0807