[英]How to comma separate a string read from a file and then saving it in an array
This is the text file that i have created 这是我创建的文本文件
NameOfProduct,Price,Availability. 产品名称,价格,可用性。
Oil,20$,yes 油,$ 20,是
Paint,25$,yes 颜料,25 $,是的
CarWax,35$,no CarWax,35 $,无
BrakeFluid,50$,yes BrakeFluid,50 $,是的
I want to read this data from the file line by line and then split it on the comma(,) sign and save it in an array of string. 我想逐行从文件中读取此数据,然后将其在逗号(,)符号上拆分,然后将其保存在字符串数组中。
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;
}
} }
The problem: 问题:
when i remove the comment on the line that print token, all of the data is printed perfectly , however when i try to print the contents of the array(jobcharge[]) it doesn't print anything. 当我删除打印令牌的行上的注释时,所有数据均被完美打印,但是当我尝试打印array(jobcharge [])的内容时,它不会打印任何内容。
You cannot save the lines inside the array, it can only contain one string per cell and you want to put 3, also you forgot to add the elements inside the array: 您无法将行保存在数组内,每个单元只能包含一个字符串,并且您想放置3个,而且您忘记在数组内添加元素:
You need a 2D array: 您需要一个二维数组:
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++;
}
Then you can print the array like this: 然后,您可以像这样打印数组:
for(int a= 0 ; a < 10 ; a++ )
{
for(int b= 0 ; b < 3 ; b++ )
{
cout << jobcharge[a][b] << endl;
}
}
Bear in mind that this code will completely fail is you have more than 10 lines or more than 3 items per line. 请记住,如果您有10行以上或每行3个以上的项目,此代码将完全失败。 You should check the values inside the loop.
您应该检查循环内的值。
you can fscanf()
instead 您可以改为
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.