samedi 14 avril 2018

Input string of unknown length

I wrote this program that replaces two spaces with an '*'.

How do I modify the code so that it does the same thing regardless of the string size? Is it even possible only using putchar and getchar?

#include <stdio.h>

char c;             
char buffer[256];  
int counter= 0;    
int i;             

int main()
{

while ((c = getchar()) != '\n') {  

    buffer[counter] =c;
    counter++;

    if (counter >=255||c==EOF) {
        break;
    }
 }

 for(i=0; i<256; i++) {

    if(buffer[i]== ' '&&buffer[i+1]==' ')
    { 

        buffer[i]= '*';

        putchar(buffer[i]); 

        i = i + 2; 

        continue; 
    }
    putchar(buffer[i]); 
}

putchar('\n'); 
return 0;
}

Aucun commentaire:

Enregistrer un commentaire