2013-10-08 52 views
0

我試圖讓我的程序打印字母而不是數字。我用char c = static_cast<char>(N);試圖做到這一點,但它不會工作,而是打印不是(a-z)的字符圖像。我如何才能將數字打印爲字母?將整數轉換爲字符

#include <cstdlib> 
#include <iostream> 
using namespace std; 

// Function getUserInput obtains an integer input value from the user. 
// This function performs no error checking of user input. 
int getUserInput() 
{ 
    int N(0); 

    cout << endl << "Please enter a positive, odd integer value, between (1-51): "; 
    cin >> N; 
    if (N < 1 || N > 51 || N % 2 == 0) 
    { 
     cout << "Error value is invalid!" << "\n"; 
     cout << endl << "Please enter a positive, odd integer value, between (1-51): "; 
     cin >> N; 
     system("cls"); 
    } 

    cout << endl; 
    return N; 
} // end getUserInput function 

// Function printDiamond prints a diamond comprised of N rows of asterisks. 
// This function assumes that N is a positive, odd integer. 
void printHourglass(int N) 
{ 
    char c = static_cast<char>(N); 
    for (int row = (N/2); row >= 1; row--) 
    { 
     for (int spaceCount = 1; spaceCount <= (N/2 + 1 - row); spaceCount++) 
      cout << ' '; 
     for (int column = 1; column <= (2 * row - 1); column++) 
      cout << c; 
     cout << endl; 
    } // end for loop 
    // print top ~half of the diamond ... 
    for (int row = 1; row <= (N/2 + 1); row++) 
    { 
     for (int spaceCount = 1; spaceCount <= (N/2 + 1 - row); spaceCount++) 
      cout << ' '; 
     for (int column = 1; column <= (2 * row - 1); column++) 
      cout << c; 
     cout << endl; 
    } // end for loop 

    // print bottom ~half of the diamond ... 


    return; 
} // end printDiamond function 

int main() 
{ 
    int N = 1; 

    while (N == 1) 
    { 
     printHourglass(getUserInput()); 
     cout << endl; 
     cout << "Would you like to print another hourglass? (1 = Yes, 0 = No):"; 
     cin >> N; 
    } 
} // end main function 
+0

更換cout << N看看'::性病:: to_string',忘了舊的方法。 – user1095108

+0

你想打印哪些字母? –

+0

我希望它能夠根據for循環打印正在遞增和遞增的字母。例如:「ABCDCBA」 –

回答

0

字母不與A開始1或任何類似的編號。您可能使用ASCII/UTF-8系統。所以,在printHourglass,與

cout << static_cast<char>('A' + count - 1); 
0
  1. C函數,itoa
  2. C++,使用字符串流
  3. 的boost :: lexical_cast的

其實對於你的情況,你可以直接打印出來。 cout << N

+0

我改變了cout << c到cout << N,它仍然打印出數字,小時玻璃形狀已關閉。 –