簡體   English   中英

如何用逗號分隔從文件中讀取的字符串,然后將其保存在數組中

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM