Thread: Help needed, very close to working

  1. #1
    Registered User
    Join Date
    Oct 2009
    Posts
    28

    Help needed, very close to working

    Hey im writing a programme that gets a string, and stores in in an array and then outputs each word on a single line, with no spaces and no blank lines.
    So far i have this:
    Code:
      char line[100];
      int i;
    
      printf("Enter a line of text (max of 100 chars): ", line);
      gets(line);
    
      for(i = 0; line[i]!='\0'; i++)
        {if(line[i]!=' ' )
           putchar(line[i]);
          else
          printf("\n");
        }
      printf("\n");
    
    }
    This works perfectly until someone puts in a double space, and then it will output a blank line, i have tried many things so it will not out put a blank line but cant seem to get anywhere.
    Can someone please help.
    Thanks Trueman

  2. #2
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    You will need to make it skip consecutive white space then. Something like:
    Code:
    while( line[ i ] == ' ' ) i++;

    Quzah.
    Hope is the first step on the road to disappointment.

  3. #3
    Registered User
    Join Date
    Oct 2009
    Posts
    28
    ok i will try that, is the while loop instead of the for loop??

  4. #4
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    No, you'd need to put that inside your check to see if you had encountered a space. If you have, then you want to try to skip them. Of course you may want to add to the != '\0' check into that as well. Basically what you're doing is: "Hey, I found a space. If we keep finding spaces from this point immediately onward, let's skip all those!"


    Quzah.
    Hope is the first step on the road to disappointment.

  5. #5
    Registered User
    Join Date
    Oct 2009
    Posts
    28
    ok thanks
    i had me try one way and a mate try your way, and it worked great, thanks

  6. #6
    Registered User
    Join Date
    Oct 2009
    Posts
    28
    sorry bit early on the saying it worked, it works as in doesnt display the blank lines anymore,
    however it does cut off one word, so for example if i was going to type, hello world, it would output:
    Hello
    orld

    any idea why this could be happening?

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 9
    Last Post: 05-26-2009, 12:40 PM
  2. Coding Problem-Help needed
    By taimurdar in forum C Programming
    Replies: 4
    Last Post: 07-07-2005, 09:47 AM
  3. Help Needed - Window won't close
    By DZeek in forum C++ Programming
    Replies: 12
    Last Post: 03-06-2005, 07:24 PM
  4. working out...
    By TechWins in forum A Brief History of Cprogramming.com
    Replies: 11
    Last Post: 04-10-2003, 10:20 AM
  5. Ghost in the CD Drive
    By Natase in forum A Brief History of Cprogramming.com
    Replies: 17
    Last Post: 10-12-2001, 05:38 PM