By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
446,238 Members | 1,746 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 446,238 IT Pros & Developers. It's quick & easy.

Remove extra blanks from a string

P: 2
Hi Experts

I am trying to get the following program running correctly. I would like to be able to input a line of text containing multiple space characters between words and have the program remove any number of excess space characters so that the sentence is rewritten correctly containing only 1 space character between individual words. However this program outputs each word on a separate line! Is there a problem with my loop?

Many thanks

Expand|Select|Wrap|Line Numbers
  1. int main(int argc, char **argv)
  2. {
  3.  AnsiString Line;
  4.  int Index;
  5.  
  6. Line = ReadStringPr("Enter your text. It must not finish with a space character." );
  7. Index = 1;
  8. //read each char of Line
  9.  
  10. while (Index <= Length(Line))
  11. {
  12.    //if current char is not a space
  13.    if (Line[Index] != ' ')//;
  14.       {
  15.       //write current char to screen
  16.       WriteChar(Line[Index]);
  17.       Index = Index + 1;
  18.       }
  19.    else //if current char is a space
  20.       {
  21.             WriteStringCr(' ');
  22.       }
  23.       //ignore all consecutive spaces
  24.       while (Line[Index] == ' ')//;  this semicolon may have created an infinite loop not allowing anything to print to screen
  25.         Index = Index + 1;
  26.  
  27.  getchar();  // to keep the display on until you press Enter key
  28.  return 0;
  29.  }
Mar 21 '07 #1
Share this Question
Share on Google+
3 Replies


Expert 100+
P: 1,510
have you a } in the wrong place?
Expand|Select|Wrap|Line Numbers
  1. else //if current char is a space
  2. {
  3. WriteStringCr(' ');
  4. }  <<< should this
  5. //ignore all consecutive spaces
  6. while (Line[Index] == ' ')//; this semicolon may have created an infinite loop not allowing anything to print to screen
  7. Index = Index + 1;
  8. <<  be here????
  9.  
Mar 21 '07 #2

P: 2
Unfortunately moving this brace does not change anything. The words are still written one on each line and not as a corrected sentence. Braces seem to be the root of all evils!!
Mar 21 '07 #3

Ganon11
Expert 2.5K+
P: 3,652
What is the difference between WriteChar() and WriteStringCr()? Does one of them always output a newline character after execution?
Mar 21 '07 #4

Post your reply

Sign in to post your reply or Sign up for a free account.