Форум программистов
 

Восстановите пароль или Зарегистрируйтесь на форуме, о проблемах и с заказом рекламы пишите сюда - alarforum@yandex.ru, проверяйте папку спам!

Вернуться   Форум программистов > C/C++ программирование > Общие вопросы C/C++
Регистрация

Восстановить пароль
Повторная активизация e-mail

Купить рекламу на форуме - 42 тыс руб за месяц

Ответ
 
Опции темы Поиск в этой теме
Старый 21.02.2010, 22:23   #1
Matr1x
Студент
Пользователь
 
Аватар для Matr1x
 
Регистрация: 10.11.2009
Сообщений: 49
По умолчанию strtok

Здраствуйте, не понимаю принцип работы функции strtok.., есть пример из msdn, закомментируйте подробно по русски пожалуйста. Заранее большое спасибо.
Код:
#include <iostream>
#include <string.h>
#include <stdio.h>
using namespace std;

int main()
{
	char string[]="A string\tof ,,tokens\nand some  more tokens";
	char seps[]=" ,\t\n";
	char *token;
	cout<<"Tokens :"<<endl;
	// Establish string and get the first token:
	token=strtok(string,seps); // C4996
	// Note: strtok is deprecated; consider using strtok_s instead
	while(token!=NULL)
	{
		// While there are tokens in "string"
		cout<<token<<endl;
		// Get next token:
		token=strtok(NULL,seps); // C4996
	}
	return 0;
}
Matr1x вне форума Ответить с цитированием
Старый 21.02.2010, 23:11   #2
spamer
Software Developer
Старожил
 
Аватар для spamer
 
Регистрация: 19.12.2008
Сообщений: 2,070
По умолчанию

Вот почитай, может поможет - http://devoid.com.ua/functions-about...ns/strtok.html
Будь проще и люди к тебе потянутся
spamer вне форума Ответить с цитированием
Старый 21.02.2010, 23:13   #3
pproger
C++ hater
СтарожилДжуниор
 
Аватар для pproger
 
Регистрация: 19.07.2009
Сообщений: 3,336
По умолчанию

2Matr1x
man strtok
Цитата:
DESCRIPTION
The strtok() function parses a string into a sequence of tokens. On the first call
to strtok() the string to be parsed should be specified in str. In each subsequent
call that should parse the same string, str should be NULL.

The delim argument specifies a set of characters that delimit the tokens in the
parsed string. The caller may specify different strings in delim in successive
calls that parse the same string.

Each call to strtok() returns a pointer to a null-terminated string containing the
next token. This string does not include the delimiting character. If no more
tokens are found, strtok() returns NULL.

A sequence of two or more contiguous delimiter characters in the parsed string is
considered to be a single delimiter. Delimiter characters at the start or end of
the string are ignored. Put another way: the tokens returned by strtok() are
always non-empty strings.

The strtok_r() function is a reentrant version strtok(). The saveptr argument is a
pointer to a char * variable that is used internally by strtok_r() in order to
maintain context between successive calls that parse the same string.

On the first call to strtok_r(), str should point to the string to be parsed, and
the value of saveptr is ignored. In subsequent calls, str should be NULL, and
saveptr should be unchanged since the previous call.

Different strings may be parsed concurrently using sequences of calls to strtok_r()
that specify different saveptr arguments.

RETURN VALUE
The strtok() and strtok_r() functions return a pointer to the next token, or NULL
if there are no more tokens.
вот сначала скажи, что тут может быть непонятного, а я объясню
I invented the term Object-Oriented, and I can tell you I did not have C++ in mind. (c)Alan Kay

My other car is cdr.

Q: Whats the object-oriented way to become wealthy?
A: Inheritance
pproger вне форума Ответить с цитированием
Старый 22.02.2010, 08:55   #4
Matr1x
Студент
Пользователь
 
Аватар для Matr1x
 
Регистрация: 10.11.2009
Сообщений: 49
По умолчанию

Цитата:
Сообщение от spamer Посмотреть сообщение
Вот почитай, может поможет - http://devoid.com.ua/functions-about...ns/strtok.html
большое спасибо!
Цитата:
Сообщение от pproger Посмотреть сообщение
вот сначала скажи, что тут может быть непонятного, а я объясню
Код:
token=strtok(string,seps); // C4996
// Note: strtok is deprecated; consider using strtok_s instead
while(token!=NULL)
{
	// While there are tokens in "string"
	cout<<token<<endl;
	// Get next token:
	token=strtok(NULL,seps); // C4996
}
спасибо, один единственный вопрос), почему во втором цикле значение первого аргумента strtok - NULL?

Последний раз редактировалось Matr1x; 22.02.2010 в 08:58.
Matr1x вне форума Ответить с цитированием
Старый 22.02.2010, 12:37   #5
RoS
Форумчанин
 
Аватар для RoS
 
Регистрация: 13.12.2009
Сообщений: 272
По умолчанию

Потому что так устроена функция - разбивать уже не новую строку, а старую, Null
Если я помог вам - порадуйте меня, нажмите на весы слева
RoS вне форума Ответить с цитированием
Старый 18.02.2012, 20:34   #6
rmv240899
Форумчанин
 
Регистрация: 18.02.2012
Сообщений: 155
Вопрос Что случилось с этой функцией

У меня вообще функция не работает: циклится

Последний раз редактировалось rmv240899; 18.02.2012 в 20:35. Причина: ...
rmv240899 вне форума Ответить с цитированием
Ответ


Купить рекламу на форуме - 42 тыс руб за месяц

Опции темы Поиск в этой теме
Поиск в этой теме:

Расширенный поиск


Похожие темы
Тема Автор Раздел Ответов Последнее сообщение
си. strtok. RZMTZM Общие вопросы C/C++ 2 05.01.2010 12:59