Visualizzazione dei risultati da 1 a 4 su 4
  1. #1
    Utente di HTML.it
    Registrato dal
    Feb 2003
    Messaggi
    1,965

    Conversione da intero a stringa

    Tratto da un libro
    Converting an integer value to a string of characters takes even more effort. The algorithm for the conversion is the following:

    1- Initialize a string to the empty string.

    2- If the integer value is zero, then output a 0, and the algorithm is complete.

    3- Divide the current integer value by ten, computing the remainder and quotient.

    4-Convert the remainder (always in the range 0..9) to a character, and concatenate the character to the end of the string.

    5- If the quotient is not zero, make it the new value and repeat steps 3-5.

    6- Output the characters in the reverse order they were placed into the string.
    Ho provato a fare

    codice:
    	int i=0,a,d=0;
    	char str2[3];
    
    	for(a=2;a>=0 && i%10!=0;a--){
    		d=i%10;
    		i/=10;
    		str2[a]=(char)d;
    	}
    	printf("Stringa -> %s\n\n",str2);
    Ma mi ritornano caratteri strani, dove ho sbagliato?

  2. #2
    Non puoi convertire un numero decimale in ASCII con un semplice cast a char...devi fare il trucco inverso del tuo post sul significato si str[a] - '0' cioè:
    codice:
    str2[a]=(char)(d + '0');
    oppure che è la stessa cosa
    str2[a]=(char)(d + 48);
    Comunque in un post recente di questo forum veniva proprio dato l'algoritmo di cui parli tu...aveva il titolo '[C] Scrivere una propria versione di itoa...perchè mai questo dovrebbe funzionare!?!?'


  3. #3
    scusate ma fare semplicemente

    codice:
    char str[16];
    int numero=27;
    
    sprintf(str,"%d",numero);
    non sarebbe più semplice e veloce?
    Purtroppo bisogna imparare che il computer non sbaglia...fa solo quello che gli dici di fare

    www.netpolaris.it

  4. #4
    Utente di HTML.it
    Registrato dal
    Feb 2003
    Messaggi
    1,965
    Originariamente inviato da fastcoder
    Non puoi convertire un numero decimale in ASCII con un semplice cast a char...devi fare il trucco inverso del tuo post sul significato si str[a] - '0' cioè:
    codice:
    str2[a]=(char)(d + '0');
    oppure che è la stessa cosa
    str2[a]=(char)(d + 48);
    Comunque in un post recente di questo forum veniva proprio dato l'algoritmo di cui parli tu...aveva il titolo '[C] Scrivere una propria versione di itoa...perchè mai questo dovrebbe funzionare!?!?'

    AAAAH giusto... Ok.

    Grazie!

Permessi di invio

  • Non puoi inserire discussioni
  • Non puoi inserire repliche
  • Non puoi inserire allegati
  • Non puoi modificare i tuoi messaggi
  •  
Powered by vBulletin® Version 4.2.1
Copyright © 2025 vBulletin Solutions, Inc. All rights reserved.