0

这是我创建的文本文件

产品名称、价格、供货情况。

油,20 美元,是
油漆,25 美元,是
汽车蜡,35 美元,没有
制动液,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;
}

}

问题:

当我删除打印令牌行上的注释时,所有数据都被完美打印,但是当我尝试打印数组的内容(jobcharge [])时,它什么也不打印。

4

2 回答 2

1

您不能将行保存在数组中,每个单元格只能包含一个字符串,并且您想放置 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 个项目,则此代码将完全失败。您应该检查循环内的值。

于 2013-06-05T14:05:28.160 回答
0

你可以fscanf()改为

char name[100];
char price[16];
char yesno[4];

while (fscanf(" %99[^,] , %15[^,] , %3[^,]", name, price, yesno)==3) {
     ....
}
于 2013-06-05T14:02:38.607 回答