# C++ String to all conversion.... Help needed...



## aditya.shevade (Mar 6, 2008)

I have a problem with conversion of a C++ string into an integer and float. We had a competition, the program given was to convert a string into respective characters, strings, integers and floats.

It means that, if the input stream is say, 'xy st 45 s g 5.36 24' then, the characters will be 's' and 'g'. Strings will be 'xy' and 'st'. The integers will be 45 and 24 and the float will be 5.36.

Is there any way to do this?

Please, please help me.

Aditya


----------



## QwertyManiac (Mar 6, 2008)

I can give a simple algorithm style Python to do this:


```
def Detect(strElement):
    intNumbers = 0
    strNumbers = "0123456789"
    if "." in strElement:
        try:
            return float(strElement)
        except:
            pass
        # We check for '.' in the input, and return a float
        # if possible. Hence the try and catch method, since
        # float() might return an exception in case it
        # encounters an alphabet along with the dot.
    else:
        for i in range(0, len(strElement)):
            # For each character in strElement
            if strElement[i] in strNumbers:
                # Keep incrementing for each element which is
                # a number. (Character present in strNumbers).
                intNumbers+=1
        # End loop
        if intNumbers==len(strElement):
            # If entire string is numbers.
            return int(strElement)
        else:
            # Its a string, if not an int or float as above.
            return str(strElement)

# Main Program follows.

if __name__=='__main__':
    strINP = raw_input("Enter the string: ")
    # Takes a raw string input from STDIN.

    lstINP = strINP.split(' ')
    # Splits the input at every space and creates a list
    # out of each element thus retrieved.

    lstFinal = map(Detect,lstINP)
    # Perform the Detect function for each element in the list.

    print lstFinal
    # Prints a list with different data types as
    # converted and returned.
```

You would need a similar type of method, of checking each input part (Upto a space and after it, and so on) and adding each of the returned values into a list/array of a defined datatype such as Float, Int or String since C++ doesn't support a list which can hold multiple data types I guess.

Sample run:

```
Enter the string: x 24 566 45.4 tt5
['x', 24, 566, 45.399999999999999, 'tt5']
```


----------



## aditya.shevade (Mar 6, 2008)

^^ Good program. But unfortunately, I want C or C++ code. And I am not going to start learning python until late this month maybe.


----------



## QwertyManiac (Mar 6, 2008)

I wasn't asking you to learn Python, I was just giving you an idea of how you'd implement it. You may also try Boost libraries for lists, conversions etc.


----------



## aditya.shevade (Mar 6, 2008)

Thanks dude.

Here, I have sorted out the first thing. The characters can be separated now.


```
#include <iostream>
#include <string.h>
#include <ctype.h>

using namespace std;

class Convert
{
	private:
		string input;
		int integers[100];
		float floats[100];
		char characters[100];
		string strings[100];
		
	public:
		void copyInput(string inputString);
		void putIntegers();
		void putFloats();
		void putCharacters();
		void putStrings();
		
};

Convert x;

int main() 
{
	string inString;
	
	cout << endl << "Please enter the input stream" << endl;
	getline(cin, inString);
	x.copyInput(inString);
	x.putCharacters();
	
	return 0;
}

/* This function copies the input string into the member string of the class */
void Convert::copyInput(string inputString)
{
	input = inputString;
}

/* Here the member string is checked for individual characters and they are 
 * inserted in the array of characters */ 
void Convert::putCharacters(void)
{
	int i=0, x=0 ;
	while(x < input.length())
	{
		/* Proceed if the element is a character. */
		if(isalpha(input[x])!=0) 
		{
			/* Proceed if the element has white space before and after it */
			if((isspace(input[x+1])!=0 && isspace(input[x-1])!=0)||(input[x+1]=='\0' && isspace(input[x-1])!=0)) 
			{
				characters[i] = input[x];
				i++;
				characters[i] = ' ';
				i++;
			}
			
		}
		x++;
	}
	
	for(int j=0; j<i; j++)
		cout << characters[j];
}
```

And the sample run is

```
Please enter the input stream
Aditya S DG E RHR A
S E A
```

I cannot figure out the rest of them


----------



## QwertyManiac (Mar 6, 2008)

Ok I did it for you, took me a long time, hope it was worth it!


```
#include <iostream>
#include <string>
#include <list>

using namespace std;

class Convert
{
    private:
        string input;
        list<string> listSplit;
        
        list<int> listInteger;
        list<string> listString;
        list<float> listFloat;
        
    public:
        Convert(string inputString)
        {
            input = inputString;
        }
        
        void performCheck()
        {
            createSplitArray();
            checkType();
            createResult();
        }
        
        void createSplitArray()
        {
            string s=input+" ", getString;
            while (s!="")
            {
                listSplit.push_back(s.substr(0,s.find(" ")));
                s.erase(0,s.find(" ")+1);
            }
        }
        
        int checkNumber(char test)
        {
            int x = int(test);
            if (x<58 && x>47 || x==46)
                return 1;
            return 0;
        }
        
        void checkType()
        {
            string x;
            char y;
            int checklen(0), len(0);
            list<string>::iterator i;
            for (i=listSplit.begin() ; i!=listSplit.end() ; i++)
            {
                x = *i;
                checklen = 0;
                len = x.length();
                string::iterator j;
                for (j=x.begin() ; j<x.end() ; j++)
                {
                    y = *j;
                    if(checkNumber(y)==0)
                    {
                        listString.push_back(x);
                        break;
                    }
                    else
                    {
                        checklen++;
                    }
                }
                if(checklen==len && x.find(".")==string::npos)
                {
                    listInteger.push_back(atoi(x.c_str()));
                }
                else if(checklen==len && x.find(".")!=string::npos)
                {
                    listFloat.push_back(atof(x.c_str()));
                }            
            }
        }
        
        void createResult()
        {
            list<string>::iterator i;
            list<int>::iterator j;
            list<float>::iterator k;
            
            cout<<"Strings are: ";
            for (i=listString.begin() ; i!=listString.end() ; i++)
                cout<<*i<<" ";
            cout<<endl;
            
            cout<<"Integers are: ";
            for (j=listInteger.begin() ; j!=listInteger.end() ; j++)
                cout<<*j<<" ";
            cout<<endl;
            
            cout<<"Floats are: ";
            for (k=listFloat.begin() ; k!=listFloat.end() ; k++)
                cout<<*k<<" ";
            cout<<endl;
        }
};

int main()
{
    Convert a("X YZ 55 58.6 32j 44.k");
    a.performCheck();
    return 0;
}
```

Output:


```
Strings are: X YZ 32j 44.k 
Integers are: 55 
Floats are: 58.6
```

For the input: X YZ 55 58.6 32j 44.k

And you have those content in the lists of the classes as well. 

PS.0: Was a learning experience for me. Never coded > 100 lines in C++ until today. I've been a fan of C and Python alone and shall continue to be so, even after this. 

PS.1: I'll leave the characters part and minor fixes to you.


----------



## aditya.shevade (Mar 6, 2008)

^^ Hey thanks man. Thank you very much.

Problem was that I have not studied data structures. So I don't know anything about lists and stuff. 

It seems that I will have to learn then ASAP.

Thanks again.

Aditya

BTW, I don't understand a single thing... But the program works though... I guess that makes it a brilliant code


----------



## QwertyManiac (Mar 6, 2008)

Heh, np. Algorithm's the same:

1. Get input string.
2. Split it for each space found and store it in an array (Here we use a List, nearly the same, only supports a lot of operations inbuilt.)
3. For each element in the list, we analyze the content of the string.
4. Post analyzing, the converted data types are put into their respective lists.
5. The lists are output.


----------



## aditya.shevade (Mar 6, 2008)

^^ Now I am getting it... bit by bit.. or byte by byte


----------

