[英]How to comma separate a string read from a file and then saving it in an array
这是我创建的文本文件
产品名称,价格,可用性。
油,$ 20,是
颜料,25 $,是的
CarWax,35 $,无
BrakeFluid,50 $,是的
我想逐行从文件中读取此数据,然后将其在逗号(,)符号上拆分,然后将其保存在字符串数组中。
string findProduct(string nameOfProduct)
{
string STRING;
ifstream infile;
string jobcharge[10];
infile.open ("partsaval.txt"); //open the file
int x = 0;
while(!infile.eof()) // To get you all the lines.
{
getline(infile,STRING); // Saves the line in STRING.
stringstream ss(STRING);
std::string token;
while(std::getline(ss, token, ','))
{
//std::cout << token << '\n';
}
}
infile.close(); // closing the file for safe handeling if another process wantst to use this file it is avaliable
for(int a= 0 ; a < 10 ; a+=3 )
{
cout << jobcharge[a] << endl;
}
}
问题:
当我删除打印令牌的行上的注释时,所有数据均被完美打印,但是当我尝试打印array(jobcharge [])的内容时,它不会打印任何内容。
您无法将行保存在数组内,每个单元只能包含一个字符串,并且您想放置3个,而且您忘记在数组内添加元素:
您需要一个二维数组:
string jobcharge[10][3];
int x = 0;
while(!infile.eof()) // To get you all the lines.
{
getline(infile,STRING); // Saves the line in STRING.
stringstream ss(STRING);
std::string token;
int y = 0;
while(std::getline(ss, token, ','))
{
std::cout << token << '\n';
jobcharge[x][y] = token;
y++;
}
x++;
}
然后,您可以像这样打印数组:
for(int a= 0 ; a < 10 ; a++ )
{
for(int b= 0 ; b < 3 ; b++ )
{
cout << jobcharge[a][b] << endl;
}
}
请记住,如果您有10行以上或每行3个以上的项目,此代码将完全失败。 您应该检查循环内的值。
您可以改为fscanf()
char name[100];
char price[16];
char yesno[4];
while (fscanf(" %99[^,] , %15[^,] , %3[^,]", name, price, yesno)==3) {
....
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.