2013-10-08 3 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

Посмотрите на ':: станд :: to_string', забывают методы унаследованных. – user1095108

+0

Какие буквы вы хотите распечатать? –

+0

Я хочу, чтобы он печатал буквы, которые увеличиваются и деинкрементируются в соответствии с циклами for. Пример: «ABCDCBA» –

ответ

0

Буквы не нумеруются A, начиная с 1 или ничего подобного. Вероятно, вы используете систему ASCII/UTF-8. Так, в printHourglass, замените cout << N с

cout << static_cast<char>('A' + count - 1); 
0
  1. C функции, itoa
  2. C++, используя stringstream
  3. подталкивание :: lexical_cast

На самом деле для вашего дела, вы можете сразу распечатать его. cout << N

+0

Я изменил cout << c до cout << N, и он все еще печатал цифры, а форма часа часа была выключена. –

Смежные вопросы