Ir para conteúdo

POWERED BY:

Arquivado

Este tópico foi arquivado e está fechado para novas respostas.

Renato Utsch

[Resolvido] [Código] Converter números para texto em C+

Recommended Posts

Olá!

 

Bom... estava fazendo um exercício de um livro meu, que estou lendo para aprimorar meus conhecimentos, e me deparei com um probleminha que me deu muita dor de cabeça... se alguém estiver com dúvidas quanto a isso, é só dar uma checada ;D

 

PS: O programa não faz a checagem para ver se são só números ou se há caracteres inválidos... Sinta-se livre para adicionar caso queira. Só peço para postar aqui depois xD

 

Aqui a questão do livro:

Write a program that converts numbers to words. Example: 895 results in "eight nine five."

 

Abaixo o código:

 

convert-numbers-to-text.cpp

/********************************************************
* convert-numbers-to-text -- program to convert        *
*     numbers to words.                                *
*                                                      *
* Author: LordEvil                                     *
*                                                      *
* Purpose: Exercise of a book                          *
*                                                      *
* License: GNU GPL v3                                  *
*                                                      *
* Usage:                                               *
*      Run the program, do what the program say to do. *
********************************************************/


#include <iostream>
#include <string>

int main()
{
// >>>>>>>>>>>> Local variable declaration  <<<<<<<<<<<<<<<< \\ 
std::string input_from_console;			// Number that will be input by stdin
register int iterator = 0;				// Iterator for loops...


// Starts the while loop for inputting
while(true)
{

	// >>>>>>>>>>>> Gets the value to calculate <<<<<<<<<<<<<<<< \\ 

	std::cout << "Please type one number (type 0 to exit): ";
	std::getline(std::cin, input_from_console);

	// >>>>>>>>>>>> Calculates the value  <<<<<<<<<<<<<<<< \\ 

	// Uses the algorithim and calculates:

	// If is 0, or wasn't input any value, exits:
	if( !input_from_console.size() || (input_from_console.size() == 1 && input_from_console.at(0) == '0') )
		break;

	// Loop continue while input_from_console has characters.
	for(iterator = 0; (unsigned) iterator < input_from_console.size(); ++iterator)
	{
		// Prints the characters			
		switch( input_from_console.at(iterator) )
		{
			case '-':
				// If is this character, couts the equivalent of it in letters...
				std::cout << " Minus ";
				break;


			case '0':
				// If is this number, couts the equivalent of it in letters...
				std::cout << " Zero ";
				break;

			case '1':
				// If is this number, couts the equivalent of it in letters...
				std::cout << " One ";
				break;

			case '2':
				// If is this number, couts the equivalent of it in letters...
				std::cout << " Two ";
				break;

			case '3':
				// If is this number, couts the equivalent of it in letters...
				std::cout << " Three ";
				break;

			case '4':
				// If is this number, couts the equivalent of it in letters...
				std::cout << " Four ";
				break;

			case '5':
				// If is this number, couts the equivalent of it in letters...
				std::cout << " Five ";
				break;

			case '6':
				// If is this number, couts the equivalent of it in letters...
				std::cout << " Six ";
				break;

			case '7':
				// If is this number, couts the equivalent of it in letters...
				std::cout << " Seven ";
				break;

			case '8':
				// If is this number, couts the equivalent of it in letters...
				std::cout << " Eight ";
				break;

			case '9':
				// If is this number, couts the equivalent of it in letters...
				std::cout << " Nine ";
				break;

			default:
				// Wow, strange error...
				std::cout << " Value Invalid! ";
				break;
		}
	}

	std::cout << "\n\n";
}

return 0;
}

 

 

Abraços :D

Compartilhar este post


Link para o post
Compartilhar em outros sites

Para quem prefere C:

 

/*

    Copyright 2013 Mateus G. Pereira
    
    Este programa é um software livre; você pode redistribui-lo e/ou 
    modifica-lo dentro dos termos da Licença Pública Geral GNU como 
    publicada pela Fundação do Software Livre (FSF); na versão 2 da 
    Licença, ou (na sua opnião) qualquer versão.

    Este programa é distribuido na esperança que possa ser  util, 
    mas SEM NENHUMA GARANTIA; sem uma garantia implicita de ADEQUAÇÂO a qualquer
    MERCADO ou APLICAÇÃO EM PARTICULAR. Veja a
    Licença Pública Geral GNU para maiores detalhes.

    Você deve ter recebido uma cópia da Licença Pública Geral GNU
    junto com este programa, se não, escreva para a Fundação do Software
    Livre(FSF) Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA

*/

#include <stdio.h>

static const char* const nums[] = {"zero", "um", "dois", "tres", "quatro",
                                   "cinco", "seis", "sete", "oito", "nove"};

void writeOut (int n)
{
    const char* buffer[16];
    int i = 15;
    
    if(n < 0)
    {
        fputs("menos ", stdout);
        n = -n;
    }
    
    while((i >= 0) && n)
    {
        buffer[i--] = nums[n % 10];
        n /= 10;
    }
    
    while(i++ < 15)
        printf("%s ", buffer[i]);
    fputc('\n', stdout);
}

int main (int argc, char** argv)
{
    int num;
    
    scanf("%d%*c", &num);
    writeOut(num);
    return 0;
}

Compartilhar este post


Link para o post
Compartilhar em outros sites

×

Informação importante

Ao usar o fórum, você concorda com nossos Termos e condições.