Forum     

Go Back   Digit Technology Discussion Forum > Software > Programming
Register FAQ Calendar Mark Forums Read

Programming The destination for developers - C, C++, Java, Python and the lot


Closed Thread
 
LinkBack Thread Tools Display Modes
Old 06-03-2008, 12:48 PM   #1 (permalink)
Console Junkie
 
aditya.shevade's Avatar
 
Join Date: Jun 2006
Location: USA
Posts: 991
Default C++ String to all conversion.... Help needed...


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
__________________
--- Console Junkie
aditya.shevade is offline  
Advertisements. Register and be a member of the community to get rid of them.
Advertisement

Old 06-03-2008, 05:20 PM   #2 (permalink)
Commander in Chief
 
QwertyManiac's Avatar
 
Join Date: Jul 2005
Posts: 6,658
Default Re: C++ String to all conversion.... Help needed...

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

Code:
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:
Code:
Enter the string: x 24 566 45.4 tt5
['x', 24, 566, 45.399999999999999, 'tt5']
__________________
Harsh J
www.harshj.com
QwertyManiac is offline  
Old 06-03-2008, 07:08 PM   #3 (permalink)
Console Junkie
 
aditya.shevade's Avatar
 
Join Date: Jun 2006
Location: USA
Posts: 991
Default Re: C++ String to all conversion.... Help needed...

^^ Good program. But unfortunately, I want C or C++ code. And I am not going to start learning python until late this month maybe.
__________________
--- Console Junkie
aditya.shevade is offline  
Old 06-03-2008, 07:22 PM   #4 (permalink)
Commander in Chief
 
QwertyManiac's Avatar
 
Join Date: Jul 2005
Posts: 6,658
Default Re: C++ String to all conversion.... Help needed...

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.
__________________
Harsh J
www.harshj.com
QwertyManiac is offline  
Old 06-03-2008, 07:43 PM   #5 (permalink)
Console Junkie
 
aditya.shevade's Avatar
 
Join Date: Jun 2006
Location: USA
Posts: 991
Default Re: C++ String to all conversion.... Help needed...

Thanks dude.

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

Code:
#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
Code:
Please enter the input stream
Aditya S DG E RHR A
S E A
I cannot figure out the rest of them
__________________
--- Console Junkie
aditya.shevade is offline  
Old 06-03-2008, 10:08 PM   #6 (permalink)
Commander in Chief
 
QwertyManiac's Avatar
 
Join Date: Jul 2005
Posts: 6,658
Default Re: C++ String to all conversion.... Help needed...

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

Code:
#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:

Code:
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.
__________________
Harsh J
www.harshj.com

Last edited by QwertyManiac; 06-03-2008 at 10:26 PM. Reason: Bugfixes and redundant lines removed
QwertyManiac is offline  
Old 06-03-2008, 10:42 PM   #7 (permalink)
Console Junkie
 
aditya.shevade's Avatar
 
Join Date: Jun 2006
Location: USA
Posts: 991
Default Re: C++ String to all conversion.... Help needed...

^^ 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
__________________
--- Console Junkie

Last edited by aditya.shevade; 06-03-2008 at 10:42 PM. Reason: Automerged Doublepost
aditya.shevade is offline  
Old 06-03-2008, 11:10 PM   #8 (permalink)
Commander in Chief
 
QwertyManiac's Avatar
 
Join Date: Jul 2005
Posts: 6,658
Default Re: C++ String to all conversion.... Help needed...

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.
__________________
Harsh J
www.harshj.com
QwertyManiac is offline  
Old 06-03-2008, 11:33 PM   #9 (permalink)
Console Junkie
 
aditya.shevade's Avatar
 
Join Date: Jun 2006
Location: USA
Posts: 991
Default Re: C++ String to all conversion.... Help needed...

^^ Now I am getting it... bit by bit.. or byte by byte
__________________
--- Console Junkie
aditya.shevade is offline  
Closed Thread

Bookmarks

Thread Tools
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are On


Similar Threads
Thread Thread Starter Forum Replies Last Post
Conversion pacificboy Programming 2 03-03-2008 04:29 PM
how to make the string function ? clmlbx Programming 3 25-02-2008 09:43 PM
how to extract the needed part from a string in vb.net *GandaBerunda* Programming 3 05-11-2007 01:05 PM
cant declare a string variable... geekgod Open Source 13 12-08-2006 06:09 AM
asp 'replace' string query! 144 QnA (read only) 1 30-06-2006 10:35 AM

 
Latest Threads
- by Charan
- by Sarath
- by clmlbx

Advertisement




All times are GMT +5.5. The time now is 12:53 AM.


Powered by vBulletin® Version 3.8.7
Copyright ©2000 - 2012, vBulletin Solutions, Inc.

Search Engine Optimization by vBSEO 3.3.2