Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

split text

Status
Not open for further replies.

qiqinuinaifen128

Programmer
Dec 9, 2007
20
SG
How can i split the text that key in by user, for example if the user key in "MoveForward To 123", how can i split the "MoveForward" to one field, "To" in to one field and 123 in to another field..

below is my simple print and scanf

Code:
char y;
printf("Please Enter Your Command:");
scanf("%s", &y);

Singapore Swimming Lessons
 
You can use strtok function to separate words. Be careful with string manipulation functions as they are mostly unsafe (BO). BTW your code corrupts memory.
 
example that uses gets to get input and strtok to split words:

Code:
#include <stdio.h>
#include <string.h>

int main()
{
	char buf[1024];
	char *token;
	char seps[] = " ";

	gets(buf);	//unsafe when input bigger than 1023 chars
	token = strtok(buf,seps);
	while( token != NULL )
	{
		printf( "%s\n", token );
		token = strtok( NULL, seps );
	}

	return 0;
}
 
> gets(buf); //unsafe when input bigger than 1023 chars
So use fgets() and save a disclaimer.
[tt]fgets( buf, sizeof buf, stdin );[/tt]



--
If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
 
Depending on usage watch out for stdios buffering...man setvbuf and man fflush.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top