Pregunta

This is the text file that i have created

NameOfProduct,Price,Availability.

Oil,20$,yes
Paint,25$,yes
CarWax,35$,no
BrakeFluid,50$,yes

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.

¿Fue útil?

Solución

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:

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. You should check the values inside the loop.

Otros consejos

you can fscanf() instead

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

while (fscanf(" %99[^,] , %15[^,] , %3[^,]", name, price, yesno)==3) {
     ....
}
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top