C++ C++;解析:如何在不使用getline、strtok等一次性传递所有分隔符的情况下确认一行中的多个分隔符。?
基本上,我要做的是将.txt文件转换为.csv文件。txt文件由管道“|”分隔,我必须将管道转换为逗号,并对现有的逗号“,”和双引号“,”进行一些其他例外 但是,我遇到的主要问题是.txt文件中的这种形式:||| 我应该把它变成: 但每次,斯特库斯总是把这三个管道变成一个逗号 我一直试图更深入地理解strtok_s(),以便为我的目的操纵它(在注释掉的if条件中找到),但我运气不太好。C++ C++;解析:如何在不使用getline、strtok等一次性传递所有分隔符的情况下确认一行中的多个分隔符。?,c++,text-parsing,string-parsing,C++,Text Parsing,String Parsing,基本上,我要做的是将.txt文件转换为.csv文件。txt文件由管道“|”分隔,我必须将管道转换为逗号,并对现有的逗号“,”和双引号“,”进行一些其他例外 但是,我遇到的主要问题是.txt文件中的这种形式:||| 我应该把它变成: 但每次,斯特库斯总是把这三个管道变成一个逗号 我一直试图更深入地理解strtok_s(),以便为我的目的操纵它(在注释掉的if条件中找到),但我运气不太好。 有没有不同的方式进行解析,使我可以逐个地考虑事物,或者用StrutokSh()来实现IF条件?< /强>
<强>有没有不同的方式进行解析,使我可以逐个地考虑事物,或者用StrutokSh()来实现IF条件?< /强>
这是我的密码:const int MAX_CHARS_PER_LINE = 150;
const int MAX_TOKENS_PER_LINE = 15;
const char* const DELIMITER = "|";
int main(){
// Need to comment code and split it up so it's not all in the main function
// Basically just asking for file name stuffs
cout << "Enter an existing input file name: ";
string fileName;
getline(cin, fileName);
fileName = fileName + ".txt";
cout << "Enter an output file name: ";
string output;
getline(cin, output);
output = output + ".csv";
ifstream infile;
ofstream outfile;
infile.open(fileName);
if (!infile){
cout << "File open failure!" << endl;
system("pause");
return 0;
}
outfile.open(output);
//THE MEAT OF THE CODE
while (!infile.eof()){
char buffer[MAX_CHARS_PER_LINE];
infile.getline(buffer, MAX_CHARS_PER_LINE);
int counter = 0;
const char* token[MAX_TOKENS_PER_LINE];
char * next_token;
token[0] = strtok_s(buffer, DELIMITER, &next_token);
if (token[0]){
for (counter = 1; counter < MAX_TOKENS_PER_LINE; counter++){
//if (){ <----- Wtf do I put in the if-condition?
//token[counter] = ",";
//}
//else{
token[counter] = strtok_s(NULL, DELIMITER, &next_token);
//}
if (!token[counter]){ // no more tokens put into the array
break;
}
}
}
//Basically just ignore all this stuff, a lot of tedious exceptions
for (int i = 0; i < counter; i++){
string temp = token[i];
string ultimate = "\"";
if (temp.find('"') != string::npos){
while (temp.find('"') != string::npos){
ultimate += temp.substr(0, temp.find('"'));
ultimate += "\"\"";
temp = temp.substr(temp.find('"') + 1);
}
ultimate += temp;
ultimate += "\"";
outfile << ultimate << ',';
}
else if (temp.find(',') != string::npos){
temp = "\"" + temp + "\"";
outfile << temp << ',';
}
else if (temp.compare(",") == 0){
outfile << temp;
}
else{
outfile << token[i] << ',';
}
}
outfile << endl;
}
infile.close();
outfile.close();
system("pause");
return 0;
}
const int MAX_CHARS_PER_LINE=150;
const int MAX_TOKENS_PER_LINE=15;
常量字符*常量分隔符=“|”;
int main(){
//需要注释代码并将其拆分,这样它就不在主函数中了
//基本上只是要求文件名的东西
当(!infle.eof())
时不能使用strtok\u s
。请使用。