【问题标题】:How to comma separate a string read from a file and then saving it in an array如何用逗号分隔从文件中读取的字符串,然后将其保存在数组中
【发布时间】:2013-06-05 13:58:25
【问题描述】:

这是我创建的文本文件

产品名称、价格、可用性。

石油,20 美元,是的
油漆,25 美元,是的
CarWax,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[])时,它不会打印任何内容。

【问题讨论】:

    标签: c++ arrays codeblocks string-split


    【解决方案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 个项目,则此代码将完全失败。您应该检查循环内的值。

    【讨论】:

      【解决方案2】:

      您可以改为fscanf()

      char name[100];
      char price[16];
      char yesno[4];
      
      while (fscanf(" %99[^,] , %15[^,] , %3[^,]", name, price, yesno)==3) {
           ....
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-11-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多