1,105,226 Community Members

Extracting individual character from a string

Member Avatar
haven_u
Light Poster
36 posts since Apr 2007
Reputation Points: 0 [?]
Q&As Helped to Solve: 0 [?]
Skill Endorsements: 0 [?]
 
0
 

iam trying to extract a individual character. for example, during run time the user enters 110111 as input. can any 1 help me with the code to extract these input and store them in an array as individual elements.

Member Avatar
William Hemsworth
Posting Virtuoso
1,546 posts since Mar 2008
Reputation Points: 1,339 [?]
Q&As Helped to Solve: 158 [?]
Skill Endorsements: 10 [?]
 
0
 

If it's an std::string, do mystr.c_str() to get a character array, to access an individual character, do mystr[[B]charIndex[/B]]. This is all over the web, try searching first.

Member Avatar
Ancient Dragon
Achieved Level 70
27,580 posts since Aug 2005
Reputation Points: 5,231 [?]
Q&As Helped to Solve: 3,029 [?]
Skill Endorsements: 115 [?]
Team Colleague
Featured
Sponsor
 
0
 

Are you entering them into an integer instead of character array? Yes, then use a series of % and / operators.

Member Avatar
Zjarek
Junior Poster in Training
79 posts since Oct 2009
Reputation Points: 2 [?]
Q&As Helped to Solve: 18 [?]
Skill Endorsements: 0 [?]
 
0
 

You can just use [] operator to get desired char, converting to char table (c_str method) is pointless.

Member Avatar
RunTimeError
Junior Poster in Training
54 posts since Oct 2009
Reputation Points: 0 [?]
Q&As Helped to Solve: 3 [?]
Skill Endorsements: 0 [?]
 
0
 

Fairly new at C++ but I believe something like this will work. Comments or improvements appreciated.

int main()
{
	cout << "Please enter some text below:\n";
	//string to hold user input
	string userInput;
	//user inputs info
	cin >> userInput;
	//create a char array of desired length.
        char chrArray[5];
	//loop through the string
	for(int index = 0; index < (int)userInput.length(); index++)
	{
		//if the userinput equals something 
		if(userInput[index] == '1')
		 {
			 chrArray[index] = userInput[index];
			 //just pausing so console will stay up
			 system("PAUSE");
		 }
	}
	return 0;
}
Member Avatar
haven_u
Light Poster
36 posts since Apr 2007
Reputation Points: 0 [?]
Q&As Helped to Solve: 0 [?]
Skill Endorsements: 0 [?]
 
0
 

thanks all for u'r help....

Question Answered as of 4 Years Ago by Ancient Dragon, William Hemsworth, RunTimeError and 1 other
You
This question has already been solved: Start a new discussion instead
Post:
Start New Discussion
Tags Related to this Article