2017-05-09 39 views
1

TEXTFILE内容读取线文本文件和分裂,如果它有逗号

a,b,c,d, 
efgh 
ijk1 

我希望在数组来存储,myArray的[];

myArray[0] = a; 
myArray[1] = b; 
myArray[2] = c; 
myArray[3] = d; 
myArray[4] = efgh; 
myArray[5] = ijkl; 

我做了什么

string myArray[100]; 
int array_count = 0; 

ifstream file((path+dicfile).c_str()); 
std::string str; 

while (std::getline(file, str,',')) 
{ 
    myArray[array_count] = str; // store those value in array 
    cout << str << "\n"; 
    strings.push_back(str); 
    array_count++; 
} 

的我的输出做了

myArray[0] = a; 
myArray[1] = b; 
myArray[2] = c; 
myArray[3] = d; 
myArray[4] = efghijkl; 
+0

带这些参数的'getline'获取您的行,直到下一个逗号或eof –

+1

如果输入数据正确,那么在最后两个字符串之间缺少一个逗号。 –

+0

@GeorgeNewton是的,风格是这样的,最后两个字符串会结合在一起,因为它之间没有逗号,但文本文件内容最初没有逗号在那里... – BeginProgramLife

回答

1

以下代码是一个除了每原代码分裂:预计产量将在逗号分割的基础然后按照逗号分割该行:

string myArray[100]; 
int array_count = 0; 

ifstream file((path+dicfile).c_str()); 
std::string line; 

while (std::getline(file, line)) 
{ 
    std::istringstream iss(line); 
    std::string str; 
    while (std::getline(iss, str, ',')) 
    { 
     myArray[array_count] = str; // store those value in array 
     cout << str << "\n"; 
     strings.push_back(str); 
     array_count++; 
    } 
} 
+0

第7行;应写(while std :: getline(file,line,',')) – BeginProgramLife

+0

你是对的。 – stefaanv

相关问题