[英]token in line doesn't work fail c++
以下函数适用于名为“ _filePath”的文本文件,并尝试将其切成由“;”分隔的小标记。 和“,”是这样的:
[Mickey M;12034;911416313;M;01a;9001;NULL;0;13;12;0;CPP,C;MSC,3D;FEND,BEND,SEC;]
当尝试将CPP,C
分离为少量令牌时,它不会到达下一个令牌,即MSC,3D
等。 我注意到该功能甚至没有到达以if (tokNum==1)
开头的块。
我真的需要帮助,非常感谢:D
void File::set() {
if (_filePath.is_open()) {
while (_filePath.getline(line, 250)) {
char *token; char *tokeng;
int tokNum = 0;
token = strtok(line, ";");
while (token != NULL) {
index = 0;
if (token == "NULL") token = NULL;
if (inputType == EMP){
if (tokNum == 0){
int numWord = seprateElements(token);
empKnoledge = new string[numWord];
tokeng = strtok(token, ",");
while(tokeng != NULL) {
empKnoledge[index] = tokeng;
index++;
tokeng = strtok(NULL, ",");
}
}
if (tokNum == 1){
int numWord = seprateElements(token);
empAfeild = new string[numWord];
tokeng = strtok(token, ",");
while(tokeng != NULL) {
empAfeild[index] = tokeng;
index++;
tokeng = strtok(NULL, ",");
}
}
if (tokNum == 2){
int numWord = seprateElements(token);
empPfeild = new string[numWord];
tokeng = strtok(token, ",");
while (tokeng != NULL) {
empPfeild[index] = tokeng;
index++;
tokeng = strtok(NULL, ",");
}
}
}
tokNum++;
token = strtok(NULL, ";");
}
numLine++;
}
}
getchar();
}
int seprateElements(char *line) { // check size of elements in line by counting ','
int count = 0;
while (*line++ != '\0') {
if (*line == ',') count++;
}
return count+1;
}
在C ++中,有很好的类和函数,例如std::string
, std::istringstream
和std::getline
。
第一个std::string
是您应该用于字符串的类。 第二类std::istringstream
是输入流,它处理字符串而不是文件。 最后,可以使用std::getline
函数将一行从流中获取到std::string
对象中,但是它具有一个可选参数,可用于分隔特殊字符(例如分号)上的字段。
使用这些功能,您可以像
std::string line;
while (std::getline(_filePath, line))
{
// Put the line into an input string stream
std::istrimgstream linestream(line);
std::string name;
std::string id;
// ... all other fields in the line
std::string last_field; // or whatever you want to name it
// Now extract all the fields from the line
std::getline(linestream, name, ';');
std::getline(linestream, id, ';');
// ... all other fields
std::getline(linestream, last_field); // Last field, no separator needed
// Some fields contains multiple tokens separated by comma
// Example extracts token from the last field of the line
std::istringstream tokenstream(last_field);
std::string token;
while (std::getline(tokenstream, token, ','))
{
std::cout << "Extracted token '" << token << "'\n";
}
}
在不相关的旁注中,请避免使用带下划线的您自己的符号, 在许多情况下,它们是保留的 。
使用String令牌Split,请参见以下代码。
#include<iostream>
#include<string.h>
using namespace std;
int main()
{
char str[]="Mickey M;12034;911416313;M;01a;9001;NULL;0;13;12;0;CPP,C;MSC,3D;FEND,BEND,SEC;";
char *pch = strtok (str,";,");
while (pch != NULL)
{
cout<<pch<<"\n";
pch = strtok (NULL, ";,");
}
return 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.