Thread: string manipulation problem!!!

  1. #1
    Registered User
    Join Date
    Jun 2007
    Posts
    3

    string manipulation problem!!!

    Hello all,

    I want to remove the spaces " " from a specific string.
    First I wrote this code:
    Code:
    #include <iostream>
    #include <string>
    using namespace std;
    int main ()
    {
    	string z="  hello";
    	string y;
    		for(int x=0;x<z.length();x++)
    	{
    		y=y+z[x];
    	}
    		cout<<y;
    		system("pause");
    
    }
    and it worked then I added an if statement to handle the " " in the z string.
    I added the statement into the for loop.
    Code:
    #include <iostream>
    #include <string>
    using namespace std;
    int main ()
    {
    	string z="  hello";
    	string y;
    		for(int x=0;x<z.length();x++)
    	{
    		if(z[x]!=" ") y=y+z[x];
    		
    	}
    		cout<<y;
    		system("pause");
    
    }
    But the compiler gave me this error!The error was in the new if statement I added.

    error C2446: '!=' : no conversion from 'const char *' to 'int'
    There is no context in which this conversion is possible
    .\new.cpp(10) : error C2040: '!=' : 'int' differs in levels of indirection from 'const char [2]'
    Can anyone please explain it and tell me how to overcome this problem.
    Thank you.
    Last edited by yanal; 06-14-2007 at 09:39 AM.

  2. #2
    Registered User
    Join Date
    Jan 2005
    Posts
    7,366
    A space is a character, and characters should be put in single quotes: ' '. Double quotes indicate a string of characters, which the compiler can't compare to a single character because they are different types.

  3. #3
    Registered User
    Join Date
    Jun 2007
    Posts
    3
    Thank you!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
    I spent the whole day trying to understand where is the problem!
    I am really thankful.You solved it!!!!!!!

  4. #4
    Registered User
    Join Date
    Apr 2007
    Posts
    102
    Heres your problem

    When you compare separate parts of a string, they are characters.

    " " designates an empty char* or char[].
    To fix it, just switch " " with ' '.

  5. #5
    Registered User
    Join Date
    Jun 2007
    Posts
    3
    yeah it worked Thank you all

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Message class ** Need help befor 12am tonight**
    By TransformedBG in forum C++ Programming
    Replies: 1
    Last Post: 11-29-2006, 11:03 PM
  2. Compile Error that i dont understand
    By bobthebullet990 in forum C++ Programming
    Replies: 5
    Last Post: 05-05-2006, 09:19 AM
  3. Replies: 4
    Last Post: 03-03-2006, 02:11 AM
  4. string manipulation problem
    By csj561 in forum C++ Programming
    Replies: 3
    Last Post: 03-18-2005, 11:11 PM