#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>

struct artikel {
  int artnr;
  char namn[256];
  int saldo;
  float pris;
};

char sbuff[256]; //buffer for sprintf to write to.
char buff[256]; //general string buffer

struct artikel artikel1;


  

int main (){
  int i;
  while (1){ //infinite loop

    scanf("%d", &artikel1.artnr);
    //printf("%d\n", artikel1.artnr);
    while(getchar()!='\n'){ //here the looping getchar function eliminates the remaining characters in the data stream, namely the \n character, which prevents the next read from working as intended.
      ; //the main body of the function is empty as we only require the function call 'getchar()' in the loop condition.
    }
    scanf("%[^\n]s",artikel1.namn); //[^\n] is a regular expression, meaning the 'negative character set of \n'; includes all characters except '\n'

    for (i = 0; i < strlen(artikel1.namn); i++){ //Two stage operation to convert string to upper case. Each char in string is converted and fed into 'buff' one by one, the whole string contained in 'buff' is then copied back into the struct.
      buff[i]=toupper(artikel1.namn[i]);
    }
    strcpy(artikel1.namn, buff);

    scanf("%d", &artikel1.saldo);
    scanf("%f", &artikel1.pris);
    
    FILE *fp;
    fp = fopen("artiklar.dat","w"); 
    if (fp == NULL){ //on error, "fopen" returns 'NULL'
      fprintf(stderr, "File not found.");
      exit(1);
    }else{
      sprintf(sbuff, "%d;%s;%d;%.2f;", artikel1.artnr, artikel1.namn,  artikel1.saldo,  artikel1.pris);
      fprintf(fp, "%s", sbuff);
      fclose(fp);
      printf("Successful write to file\n");
    }
  }
}
