strtok()函數(shù)
函數(shù)原型:
char * strtok(char *s, const char *delim)函數(shù)功能: 分解字符串為一組字符串,s為要分解的字符串,delim為分隔字符串。
描述:strtok()用來將字符串分割成一個個片段,參數(shù)s指向?qū)⒁环指舻淖址瑓?shù)delim則為分隔字符串,當(dāng)strtok()在參數(shù)s的字符串中發(fā)現(xiàn)到參數(shù)delim的分隔字符時,則會將該字符改為'\0'字符,在第一次調(diào)用時,strtok()必需給予參數(shù)s字符串,往后的調(diào)用則將參數(shù)s設(shè)置成NULL.每次調(diào)用成功則返回被分隔片段的指針。代碼:
#include <iostream>
#include <fstream> //C++讀寫文件的頭文件
#include <cstring>
using namespace std;
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
int main(int argc, char** argv) {
char buffer[256];
ifstream ifs;
ifs.open("phone.txt", ios::in);
if(!ifs.is_open())
{
cout << "文件打開失??!" << endl;
return 0;
}
while(!ifs.eof()) //判斷文是否到達文件末尾,如果到達文件尾返回非0值
{
ifs.getline(buffer, 100);
cout << buffer << endl;
char *tokenPrt = strtok(buffer, " ");
while(tokenPrt != NULL)
{
cout << tokenPrt << endl;
tokenPrt = strtok(NULL, " ");
}
}
ifs.close();
return 0;
}

效果圖.png