How can the isspace function be used to remove excess white space?

  • Thread starter Thread starter magnifik
  • Start date Start date
  • Tags Tags
    Function
Join the discussion
Registration is free. Ask a follow-up in this thread, or start your own.
3 replies · 2K views
magnifik
Messages
350
Reaction score
0
I am trying to remove excess white space using the isspace function. For example, I am reading text from a txt file that says:

I am super sleepy.

------------------------------
but I want it to say:

I am super sleepy.

------------------------------

I was thinking I could use the isspace(c), where c is each character being read and try to make a statement that somehow erases all but one space. Any suggestions??
 
Physics news on Phys.org
Added [ code] tags make your spaces show up.
magnifik said:
I am trying to remove excess white space using the isspace function. For example, I am reading text from a txt file that says:
Code:
I am                super sleepy.
------------------------------
but I want it to say:
Code:
I am super sleepy.
------------------------------

I was thinking I could use the isspace(c), where c is each character being read and try to make a statement that somehow erases all but one space. Any suggestions??
What I would do is read the original sentence into one character array, and then copy characters to another character array. In the copy operation, when I encountered the first space after a word, I would copy that space, but would ignore any subsequent spaces and not copy them. When I hit the first non-space character I would copy it and the subsequent characters up to the first space after the word, and so on, as before.
 
Hmm.. I tried using this segment of code in my program

Code:
			while (isspace(c))
			{
				if(!inf.get(c))
					return false;
			}

it does delete extra white space, but in the process it also deletes the first character of every word preceded by a white space...

For example, if the input text file read:

Why is this program so difficult?

The output text file prints:

Why s his rogram o ifficult?

I don't know what to do to modify my code to fix this problem...any help would be appreciated!
 
You are not using get() correctly. Here is a link to some documentation for this function: http://www.cplusplus.com/reference/iostream/istream/get/
 
Last edited by a moderator: