Replacing tabs with spaces

I want my program to replace tabs with spaces.1tab=4spaces.When i write aa(tab)aaa(tab)(tab)a(tab) it must show me aaxxaaaxxxxxaxxx. I think that my program works corectly but when a write aaa(tab)a it must show aaaxa but it is aaaxxxxxa.Please for help!!! That is my code:

#include <stdio.h>

int next_tabstop(int col) {
    return(4 - col%4);


}
int main() {
    int ch;
    int col=0;
    while((ch=fgetc(stdin))!=EOF){
        if(ch=='\n'){
            col=0;
            fputc(ch,stdout);
        } else{
            col++;
            if(ch!='\t'){
            fputc(ch,stdout);    
            }else {
                int sp=next_tabstop(col);
                col+=sp;
                while (sp>=0){
                 fputc('x',stdout);
                 sp--;
                }
                
            }
            
    }


    }


    return 0;
}

Hi
Try these:
to replace tabs with spaces (1 tab = 4 spaces)

perl -pi.bak -e "s/\t/    /g" infile

here: 1 tab = 'xxxx'

perl -pi.bak -e "s/\t/xxxx/g" infile

hope this helps
csn

Thank you, but i have to make a program for that function(school project).I edit my code, but now there is another problem. when i write on first line everything works corectly, but after that everything goes wrong.

#include <stdio.h>

int next_tabstop(int col) {
    return(4 - col%4);


}
int main() {
    int ch;
    int col=0;
    while((ch=fgetc(stdin))!=EOF){
        if(ch=='\n'){
            col=1;
            fputc(ch,stdout);
        } else{
            if(ch!='\t'){
            col++;
            fputc(ch,stdout);
            }else {
                int sp=next_tabstop(col);
                col+=sp;
                while (sp>0){
                 fputc('x',stdout);
                 sp--;
                }
                
            }
            
    }


    }


    return 0;
}

Do not post classroom or homework problems in the main forums. Homework and coursework questions can only be posted in this forum under special homework rules.

Please review the rules, which you agreed to when you registered, if you have not already done so.

More-than-likely, posting homework in the main forums has resulting in a forum infraction. If you did not post homework, please explain the company you work for and the nature of the problem you are working on.

If you did post homework in the main forums, please review the guidelines for posting homework and repost.

Thank You.

The UNIX and Linux Forums.