turning a char string into multiple chars

Started by
2 comments, last by bardock 20 years, 9 months ago
im trying to turn a char string into multiple chars something like this char word = "one two" char array[] loop code here print the first word in a char in the char array print the second word in a char in the char array anyone know how i could do this?thanks.
Advertisement
If I understand your question right, you want to cut the string "one two" into two strings "one" and "two". If this is what you want, then you should scan the string "one two" until you hit a separator, in this case a space. And then store whatever was before the space in it''s array, and then do this procedure all over again until no more words are left...

have ypou tried sscanf?

There is an ansistring equivilent aswell (if under win32 for example)

for the sscanf one, I think (haven''t used it for ages)
its something like (very bad example btw)

char word[256]="one two";
char words[2][256];
// either its the following
sscanf(word,"%c %c",words[0],words[1]);
// or maybe this
sscanf(word,"%s %s",words[0],words[1]);

I THINK it was safer to use the %c version. The format could have been %*c. It was something funny. It basically said the field was "a series of characters) if it had the * or some other symbol in there. Either way it worked better than %s if you had tabs, and non uniform strings/tokens etc.

do a search in your help files for scanf

Beer - the love catalystgood ol' homepage
Here's a nifty little function that will extract substrings out of a string and stick them in a vector

void Tokenize( const char* strSource, std::vector<std::string>& tokens, const char* delimiters ){	const char* delims = delimiters;	size_t iLength = strlen( strSource );    	if( iLength )	{		// Make copy so original dosnt get altered		char* pTemp = new char[iLength + 1]; 		std::strcpy( pTemp, strSource );		char* str = strtok( pTemp, delims );		while( str )		{			tokens.push_back( std::string( str ) );			str = strtok( NULL, delims );		}		delete [] pTemp;	}			}


What you do is this


char* s = "one two,three;four";
std::vector tokens;
Tokenize( s, tokens, " ,;" );


and when Tokenize returns the vector 'tokens' will have the elenets "one", "two", "three" and "four". The source string (strSource) will be split wherever a delimiter is found. The delimiters are a string of characters that signal to the function when it's reached an end point. In this case we have three delimiters, space, comma and semi-colon.


:::: [ Triple Buffer V2.0 ] ::::

[edited by - ifoobar on July 30, 2003 1:33:19 AM]

[edited by - ifoobar on July 30, 2003 1:34:48 AM]
[size=2]aliak.net

This topic is closed to new replies.

Advertisement