【发布时间】:2019-05-15 12:22:56
【问题描述】:
我想将文本文件每一行的字符串拆分成一个数组,类似于 python 中的 split() 函数。我想要的语法是一个循环,它将每个拆分字符串输入到数组的下一个索引中, 例如,如果我的字符串: "ab,cd,ef,gh,ij"
,每次遇到逗号时,我都会: 数据文件 >> arr1[i]
我的数组最终会: arr1 = [ab,cd,ef,gh,ij]
下面提供了一个不读取文本文件的模拟代码
#include <iostream>
#include <fstream>
#include <stdio.h>
#include <string.h>
#include <string>
using namespace std;
int main(){
char str[] = "ab,cd,ef,gh,ij"; //" ex str in place of file contents/fstream sFile;"
const int NUM = 5;
string sArr[NUM];//empty array
char *token = strtok(str, ",");
for (int i=0; i < NUM; i++)
while((token!=NULL)){
("%s\n", token) >> sArr[i];
token = strtok(NULL, ",");
}
cout >> sArr;
return 0;
}
【问题讨论】:
-
我也得到一个无效的二进制错误操作数,我认为这是因为我在指令中使用了 string.h 和 string
-
您将在这里获得有用的信息和更好的方法:stackoverflow.com/questions/5607589/…