Jump to content

What am I doing wrong?

grimreeper132

I wasn't aware you could "print" a backspace which seems useful and cool to know, so thanks for kind of teaching me that. :P

 

Now, for the program. It's actually far easier to iterate over strings in C using a pointer, since they are just arrays of characters.

 

#include <stdio.h>

int main(void) {
	
	char str[] = "These have one space between. These  have  two  spaces  between.\n";
	char* ptr = str;
	int count = 0;
	
	printf("Before:\t%sAfter:\t", str);
	
	while (*ptr) {
		
		printf("%c", *ptr);
	    if (*ptr == ' ') {
	    	
	        count++;
	        if (count == 2) {
	        	
	            count -= 2;
	            printf("\b");
	        }
	    }
	    else if (count > 0) {
	    	count--;
	    }
	    
	    ptr++;
	}

	return 0;
}

 

Here's a working version of the program.

 

You start the pointer at the beginning of the string and just increment its value by 1 each iteration of the while loop. When you find a space, you increment a counter. When the counter equals 2, you set it back to zero and backspace a character. However, you have to remember that if the character isn't a space and the previous one was a space (so when count==1 and *ptr!=' ' you have to set the counter back to zero.

Link to comment
Share on other sites

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×