Jump to content

Need some answers

- - - - -

This topic has been archived. This means that you cannot reply to this topic.
4 replies to this topic

#1
debug

debug

    Newbie

  • Members
  • PipPip
  • 17 posts
hi, i want to know in c++ how can we extract things we want from a string. for example, if a user input 3434dfgrs3345, the output will be 34343345 instead of the char. :)

#2
v0id

v0id

    Retired

  • Members
  • PipPipPipPipPipPipPipPipPip
  • 2,936 posts
Look at this:
#include <iostream>
#include <string>

std::string ExtractNumbers(std::string Source)
{
	std::string Destination = "";
	
	for(int i = 0; i < Source.length(); i++)
		if(static_cast<int>(Source.at(i)) > 47 && 
		   static_cast<int>(Source.at(i)) < 58)
			Destination += Source.at(i);
	
	return Destination;
}

int main()
{
	std::string MyStringWithChars = "3434dfgrs3345";
	std::string MyStringWithoutChars = ExtractNumbers(MyStringWithChars);
	
	std::cout << MyStringWithChars << std::endl;
	std::cout << MyStringWithoutChars << std::endl;

	return 0;
}
This could probably be done with a stringstream as well.

#3
TkTech

TkTech

    The Crazy One

  • Moderators
  • 1,396 posts
Look into the Regex library set. It can be used to extract anything from anything using simple calls. However, using functions like the one void listed above works perfectly for what you (seem) to want.

#4
debug

debug

    Newbie

  • Members
  • PipPip
  • 17 posts
thank for the reply. got another question to ask. how to change the below code into a function?

#include <iostream>
#include <cstring>
using namespace std;

int main()
{
char myAddress[100] = {0};
int i;
cout <<"Enter the address:";
cin.getline(myAddress, 40);

for(i=0; i<100; i++)
{
if(static_cast<int>(myAddress[i])>=48 && static_cast<int>(myAddress[i])<=57)
{
cout<< myAddress[i];
}
}


return 0;
}

#5
v0id

v0id

    Retired

  • Members
  • PipPipPipPipPipPipPipPipPip
  • 2,936 posts
I don't know what of the code you want to be in a function.
I don't know if you have to use C-strings neither, because if you're using C++-strings, it would be easier for you.

#include <iostream>
#include <string>

int main()
{
	std::string myAddress;
	std::cout <<"Enter the address: ";
	std::getline(std::cin, myAddress);
	std::cout << "My address:        " << myAddress << std::endl;
	return 0;
}