Pagina 1 di 2 1 2 ultimoultimo
Visualizzazione dei risultati da 1 a 10 su 16
  1. #1

    [c] Stampare In Ordine Inverso Le Parole Di Una Frase

    Buongiorno a tutti!
    L'esercizio dice:
    -prendere in input una riga di testo;
    -suddividerla in token con la funzione strtok;
    -inviarla in output in ordine inverso.

    Il mio programma è questo:
    codice:
    /* Scrivere una frase, dividerla in soket e stamparli in ordine inverso */ 
    #include <stdio.h> 
    #include <stdlib.h> 
    #include <string.h> 
    
    void reverse( char *sentence ); 
    
    main() 
    { 
          char s[100]; 
          
          printf("Inserisci una frase:\n"); 
          gets(s); 
          
          printf("La frase stampata con i token in ordine inverso e' :\n"); 
          reverse(s); 
          
          putchar('\n'); 
          system("pause"); 
    } 
    
    void reverse( char *sentence ) 
    { 
         char *tokenPtr; 
         char v[100]; 
         int i;
          
         tokenPtr = strtok(sentence, " "); 
         sprintf(v, "%s", tokenPtr); 
          
         while ( tokenPtr != NULL ) 
         { 
               tokenPtr = strtok(NULL, " "); 
               sprintf(v, "%s", tokenPtr); 
         } 
          
         i = strlen(v); 
          
         while ( i != 0 ) 
         { 
               printf("%c", v[i] ); 
               i--; 
         } 
          
    }

    La finestra dell'output mi da, dopo aver inserito la frase:

    )llun


    ...naturalmente è sbagliato... Qualcuno di voi mi può aiutare?? Grazie!!

  2. #2
    Questa è una possibile soluzione didattica, vedi se fa quello che vuoi te...


    codice:
    // Reverse sentence
    
    
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    
    
    
    
    // Prints in reverse order the words of a sentence
    void reverse( char *sentence, const char delimiter );
    
    
    
    int main( int argc, char *argv[] )
    {
    	if( argc != 2 )
    	{
    		printf( "Usage: %s <sentence>\n", argv[0] );
    		exit(EXIT_FAILURE);
    	}
    	
    	
    	reverse(argv[1], ' ');
    	
    	return 0;
    }
    
    
    
    
    // Prints in reverse order the words of a sentence
    void reverse( char *sentence, const char delimiter )
    {
    	unsigned n;					// Numbers of delimiters in the sentence
    	char *charPtr = NULL;
    	
    	
    	// Calculates the number of delimiters
    	charPtr = strchr(sentence, delimiter);
    	for( n = 0; charPtr != NULL; ++n, charPtr = strchr(charPtr+1, delimiter) );	
    	
    	// More words...
    	if( n )
    	{
    		// Allocates the word's array of pointers
    		char **rWords = (char **) malloc( (n+1) * sizeof(char *) );
    	
    		if( rWords != NULL )
    		{
    			int i = 0;
    		
    			// The brutal pointers
    			for( rWords[i] = strtok(sentence, &delimiter); i != n; rWords[i] = strtok(NULL, &delimiter) )
    				++i;
    	
    			// Prints words in reverse order
    			for( i = n; i >= 0; --i)
    				printf( "%s\n", rWords[i] );
    	
    			// Relase rWords
    			free(rWords);
    		}
    	}
    	
    	// One word
    	else
    		printf("%s\n", sentence);
    }
    Fracty - The Fractal Generator



    If you cannot choose a concise name that expresses what the method does, it is possible that your method is attempting to perform too many diverse tasks.

  3. #3
    Grazie per la tua risposta! Solo che non ho ancora studiato la malloc... Dovrei svolgere questo programma solo con puntatori, vettori e funzioni per la manipolazione delle stringhe...

  4. #4
    La soluzione può essere notevolmente semplificata secondo me... Ad esempio:

    codice:
    #include <stdio.h>
    #include <string.h>
    
    void printRevStr (char *s)
    {
    	
    	char c;
    	
    	if (*s == '\0')
    		return;
    	
    	else 
    	{
    		c = *s;
    		printRevStr (s + 1);
    		printf ("%c", c);
    	}
    
    }
    
    int main (void)
    {
    	
    	char s [50];
    	
    	printf ("\nInserire stringa: ");
    	scanf ("%s", s);
    	
    	printf ("\n\nStringa stampata all'incontrario: ");
    	printRevStr (s);
    	
    	printf ("\n\n\n");
    	return 0;
    
    }
    Se proprio vuoi usare anche <string.h>, potresti cambiare la procedura così:

    codice:
    void printRevStr (char *s)
    {
    	
    	char c;
    	
    	if (strlen(s) == 1)
    		printf ("%c", *s);
    	
    	else 
    	{
    		c = *s;
    		printRevStr (s + 1);
    		printf ("%c", c);
    	}
    
    }
    Salute a voi, da Laikius!

    --> Faber est suae quisque fortunae <--

  5. #5
    Grazie per la tua risposta! Il programma deve fare questo:
    se inserisco ciao come va deve stamparmi va come ciao


    Solo che, nel tuo programma:
    se inserisco ciao come va mi stampa oaic

    Quindi non è ancora questa la soluzione...

  6. #6
    Okok basta una piccola modifica!
    Il problema è la scanf con %s, che legge una stringa fino al primo spazio!

    Tra le variabili del main, metti anche

    codice:
    char c;
    int i = 0;
    Poi, dopo aver chiesto d'inserire una stringa, fai cosi:

    codice:
    do
    {
         scanf ("%c", &c);
         if (c != 10)
         {
               s[i] = c;
               i++;
         }
    }
    while (c != 10);
    s[i] = '\0';
    In questo modo ti legge la stringa fino alla pressione del carattere invio (10), compresi gli spazi
    Salute a voi, da Laikius!

    --> Faber est suae quisque fortunae <--

  7. #7
    Utente di HTML.it
    Registrato dal
    Jul 2008
    Messaggi
    1,326
    Molto più banalmente, per leggere una stringa anche oltre lo spazio si usa una fgets().

    Ma comunque penso che l'op volesse solo invertire l'ordine delle parole all'interno della frase, non invertire le parole stesse.
    every day above ground is a good one

  8. #8
    Originariamente inviato da Laikius91
    La soluzione può essere notevolmente semplificata secondo me... Ad esempio:
    Indubbimente, in pratica sarebbe bastato solo un puntatore a char e una scansione inversa della stringa (poche righe di codice); ma chiedeva esplicitamente l'utilizzo di strtok, inoltre la mia versone è basata essenzialmente sull'aspetto didattico.

    Fracty - The Fractal Generator



    If you cannot choose a concise name that expresses what the method does, it is possible that your method is attempting to perform too many diverse tasks.

  9. #9
    Oddio che testa che ho!
    Accidenti a me e alla mia fretta!
    Chiedo scusa davvero!
    La faccenda si complica un po'...
    Salute a voi, da Laikius!

    --> Faber est suae quisque fortunae <--

  10. #10
    Questa in pratica fa la stessa cosa, ma ovviamente non è "didattica" e non utilizza strtok, però se ti va bene lo stesso puoi usarla, non è difficile da capire:


    codice:
    void reverse( char *sentence, const char delimiter )
    {
    	char *ptr = sentence + strlen(sentence);
    	
    	while( ptr-- != sentence )
    	{
    		if( *ptr == delimiter )
    		{
    			*ptr = '\0';
    			printf( "%s\n", ptr+1 );
    		}
    	}
    	
    	printf( "%s\n", sentence );
    }
    Fracty - The Fractal Generator



    If you cannot choose a concise name that expresses what the method does, it is possible that your method is attempting to perform too many diverse tasks.

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.