1

A friend left me a code that should open 2 files solution.txt and priority.csv and generate a 3rd file result.txt as an output.

Files structures:

  • solution.txt contains an ordered list of target, names and values separated by commas, and I know how many line the file contains:
target0,name0,value0,name1,value1,name2,value2,name3,value3

target1,name4,value4,name5,value5,name6,value6,name7,value7

target2,name8,value8,name9,value9,name10,value10,name11,value11
...etc
  • some of solution.txt's lines contain only a target value:

target3

target4

target5 ...etc.

  • priority.csv contains an indexed list of colornames, I know how many colornames there are:

1,colorname1

2,colorname2

3,colorname3

The code below should do the following:

  • ask how many lines of data solution.txt contains
  • ask how many colornames are contained in priority.csv
  • put the name(s) and associated value(s) of solution.txt in the order defined by priority.csv
  • create an array that contains as many columns as the number of colors, and as many lines as in solution.txt
  • fill this array with the value(s) associated to each line & colorname
  • fill the other cases with 0

The code doesn't work for some reasons I don't understand. If you have the courage to compile it, here are examples to put in solution.txt and priority.txt :

solution.txt

99985,CIN,0.624049619347,OR0,0.36925123875,K2M,0.00387491644559,gY6D,0.00282422545715
99986,CIN,0.624372658354,OR0,0.369683600811,K2M,0.00365124527159,gY6D,0.00229249556329
99987,CIN,0.624695697361,OR0,0.370115962872,K2M,0.0034275740976,gY6D,0.00176076566943
99988,CIN,0.625018736368,OR0,0.370548324933,K2M,0.0032039029236,gY6D,0.00122903577557
99989,CIN,0.625341775375,OR0,0.370980686994,K2M,0.00298023174961,gY6D,0.00069730588171
99990,CIN,0.625664814382,OR0,0.371413049055,K2M,0.00275656057561,gY6D,0.000165575987851

priority.csv

1,CIN
2,K2M
3,gY6D
4,OR0

In this example the amonut of lines is 6 and there are 4 colors

And that's the code, I listed possible errors and I get error2 and error4 printed on the console:

#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <stdio.h>
#include <string.h>
using namespace std;


int main() {

int COLORS = 0;
int LINES = 0;

cout << endl << "Original Data (solution.txt):" << endl << endl << "How many lines?" << endl;
cin  >> LINES;
cout << "How many colors in the list?" << endl;
cin  >> COLORS;

char Coul[COLORS][LINES];

//1- reading the file priority.csv
for (int i=0; i<COLORS; i++) Coul[i][0]='\0';

FILE *Read=fopen("priority.csv","rt");

if (Read == NULL) {
        printf("Error 1");
        return(0);
}

char line[120];
int N;

for (int i=0; i<COLORS; i++)
{
  char name[8];
  fgets(line,15,Read);
  sscanf(line,"%d,%s",&N,name);
  if (N == i) strcpy(Coul[i], name);

  else {
        printf("Error 2"); // Error2
        break;
  }
}

fclose(Read);

//2- reading the file solution.txt and writing the result.
Read=fopen("solution.txt","rt");

if (Read == NULL) {
        printf("Error 3"); // Error3
        return(0);
        }

FILE *Write=fopen("result.txt","wt");

for (int i=1; i<LINES; i++)
{
  char c[4][8];  // 4 color names
  float v[4]; // 4 values
  fgets(line,119,Read);
  sscanf(line,"%d,%s,%f,%s,%f,%s,%f,%s,%f",
              &N, c[0], &v[0], c[1], &v[1], c[2], &v[2], c[3], &v[3]);
  if (N == i)
  {
    if (strlen(c[0]) == 0)  // the line is empty
    {
      fprintf(Write,"%d ",i);
      for (int i=0; i<COLORS; i++) fprintf(Write,"0 ");
      fprintf(Write,"\n");
    }
    else
    {
      fprintf(Write,"%d ",i);
      int r[4];
// we search the rang of c[ordre]
      for (int order=0; order<4; order++)
      {
        for (int ir=0; ir<COLORS; ir++)
        {
          if (strcmp(c[order], Coul[ir]) == 0) r[order]=ir;
        }
      }
      for (int ir=0; ir<r[0]; ir++) fprintf(Write,"0 ");
      fprintf(Write,"%d ",v[0]);
      for (int ir=r[0]+1; ir<r[1]; ir++) fprintf(Write,"0 ");
      fprintf(Write,"%d ",v[1]);
      for (int ir=r[1]+1; ir<r[2]; ir++) fprintf(Write,"0 ");
      fprintf(Write,"%d ",v[2]);
      for (int ir=r[2]+1; ir<r[3]; ir++) fprintf(Write,"0 ");
      fprintf(Write,"%d ",v[3]);
      for (int ir=r[3]+1; ir<57; ir++) fprintf(Write,"0 ");
      fprintf(Write,"\n");
    }
  }
  else {
      printf("Error 4");
      break;
      } //Error4
}
fclose(Write);
fclose(Read);
}

could you please help debugging? I'm lost! Adrien

3
  • 2
    why are you not using your debugger? What is the problem? How are we supposed to read a huge snippet of code and give you the solution? Try to make the snippet smaller. It will help us and optionally make you see a possible bug. Commented Aug 8, 2013 at 11:41
  • 2
    That is more of a C program than C++. Also, you really shouldn't mix e.g. printf and std::cout (they use different buffers, so e.g. flushing std::cout will not flush the output from printf). Commented Aug 8, 2013 at 11:42
  • 1
    Oh and a little hint: When declaring local variables, their values are undefined. Commented Aug 8, 2013 at 11:57

2 Answers 2

2

Since you want to allocate memory dynamically you must use new and delete in c++. So instead of char Coul[COLORS][LINES]; use these lines:

char **Coul = NULL;

Coul = new char*[COLORS];

for(int i = 0; i < COLORS; i++)
    Coul[i] = new char[LINES];

and at the end add these:

for(int i = 0; i < COLORS; i++)
    delete [] Coul[i];

delete [] Coul;

It should compile, but I couldn't get pass the &N part, because I couldn't understand what you were trying to do.

EDIT: Done!

EDIT2: If I was right to assume that opening file does not load it all into RAM, then below is RAM friendly code adapted to old code, which uses temporary files as buffers (it may be a little slower and you need more disk space).

EDIT3: Changed potentially unsafe string._Copy_s() to newly discovered string.substr()

#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <iomanip>
using namespace std;

class Sorter
{
private:
    bool save_RAM, temp1_cleared, temp2_cleared;
    string temp1, temp2;
    int COLORS, LINES;
    string *Color_codes, **Color_values;
    bool find_codename(string line, string codename)
    {
        if (line.find(codename) == -1)
            return 0;
        else
        { //checking if there are other letters, which would make this codename not full and incorrect
            char a, b;
            if (line.find(codename) == 0)
            {
                b = line[codename.length()];
                if (b == ',')
                    return 1;
                else
                    return 0;
            }
            else
            {
                a = line[line.find(codename) - 1];
                b = line[line.find(codename) + codename.length()];
                if (a == ',' && b == ',')
                    return 1;
                else
                    return 0;
            }
        }
    }
    void allocate_memory()
    {
        if (!save_RAM)
        {
            Color_codes = new string[COLORS];
            Color_values = new string*[LINES];
            for (int i = 0; i < LINES; i++)
                Color_values[i] = new string[COLORS];
        }
    }
    void deallocate_memory()
    {
        if (!save_RAM)
        {
            delete [] Color_codes;
            for (int i = 0; i < LINES; i++)
                delete [] Color_values[i];
            delete [] Color_values;
        }
        else
        {
            remove(temp1.c_str());
            remove(temp2.c_str());
        }
    }
    void clear_temporary_file(const char *filename, bool &was_cleared)
    {
        if (was_cleared)
            return;
        else
            was_cleared = true;

        ofstream temp_file(filename);

        if (temp_file == NULL) 
        {
            cout << "Error 6";
            cin.get();
            exit(EXIT_FAILURE);
        }

        temp_file.close();
    }
    void write_to_temporary_file(const char *filename, string value)
    {
        ofstream temp_file(filename, ios::app);

        if (temp_file == NULL) 
        {
            cout << "Error 5";
            cin.get();
            exit(EXIT_FAILURE);
        }

        temp_file << value << endl;
        temp_file.close();
    }
    string read_line(const char *filename, int line_number, bool twoD_array, int second_line_number, int line_length)
    {
        ifstream temp_file(filename);
        string line;

        if (temp_file == NULL) 
        {
            cout << "Error 7";
            cin.get();
            exit(EXIT_FAILURE);
        }

        if (!twoD_array)
        {
            for (int i = 0; i < line_number; i++)
                getline(temp_file, line);
            getline(temp_file, line);
        }
        else
        {
            for (int j = 0; j < second_line_number + (line_length*line_number); j++)
                getline(temp_file, line);
            getline(temp_file, line);
        }

        temp_file.close();
        return line;
    }
    void seperate_input(string line, int &N, string &Name)
    {
        string temp;
        stringstream tempbuf;
        line += ',';
        stringstream ss(line);

        getline(ss, temp, ',');
        tempbuf << temp;
        tempbuf >> N;
        tempbuf = stringstream();

        getline(ss, temp);
        tempbuf << temp;
        tempbuf >> Name;
    }
    void Generate_values(int line_number, string Other_stuff)
    {
        string temp;
        if (!save_RAM)
        {
            for (int i = 0; i < COLORS; i++)
            {
                if (find_codename(Other_stuff, Color_codes[i]))
                {
                    int j = 0;
                    bool search = true;
                    int a, b;  //find comma positions

                    a = Other_stuff.find(Color_codes[i]) + Color_codes[i].length() + 1;

                    while(search)
                    {
                        j++;
                        char c = Other_stuff[a + j];
                        if (c == ',')
                        {
                            b = a + j;
                            search = false;
                        }
                    }

                    temp = Other_stuff.substr(a, b);         // copy value to temporary buffer

                    Color_values[line_number][i] = temp;
                }
                else
                    Color_values[line_number][i] = "0";
            }
        }
        else
        {
            clear_temporary_file(temp2.c_str(), temp2_cleared);
            for (int i = 0; i < COLORS; i++)
            {
                string codename = read_line(temp1.c_str(), i, false, 0, 0);
                if (find_codename(Other_stuff, codename))
                {
                    int j = 0;
                    bool search = true;
                    int a, b;  //find comma positions

                    a = Other_stuff.find(codename) + codename.length() + 1;

                    while(search)
                    {
                        j++;
                        char c = Other_stuff[a + j];
                        if (c == ',')
                        {
                            b = a + j;
                            search = false;
                        }
                    }

                    temp = Other_stuff.substr(a, b);         // copy value to temporary buffer

                    write_to_temporary_file(temp2.c_str(), temp);
                }
                else
                    write_to_temporary_file(temp2.c_str(), "0");
            }
        }

    }
    double convert_to_double(string number)
    {
        double also_number = 0;
        stringstream ss(number);
        ss >> also_number;
        return also_number;
    }
public:
    Sorter(bool RAM_saver)
    {
        COLORS = 0;
        LINES = 0;
        Color_codes = NULL;
        Color_values = NULL;
        save_RAM = RAM_saver;
        temp1 = "temp_code.txt";
        temp2 = "temp_values.txt";
        temp1_cleared = false;
        temp2_cleared = false;
    }
    ~Sorter()
    {
        deallocate_memory();
    }
    void get_user_input()
    {
        cout << endl << "Original Data (solution.txt):" << endl << endl << "How many lines?" << endl;
        while (!(cin >> LINES))
        {
            cin.clear();
            cin.sync();
        }
        cout << "How many colors in the list?" << endl;
        while (!(cin >> COLORS))
        {
            cin.clear();
            cin.sync();
        }

        allocate_memory();
    }
    void read_priority_file(const char *filename)
    {
        ifstream priority_file(filename);

        if (priority_file == NULL) 
        {
            cout << "Error 1";
            cin.get();
            exit(EXIT_FAILURE);
        }

        string line;
        int N;

        if (!save_RAM)
        {
            for (int i = 0; i < COLORS; i++)
            {
                string Name;
                getline(priority_file, line);
                seperate_input(line, N, Name);
                if (N == (i+1)) 
                {
                    Name.pop_back();   //push last , out (I need it other function)
                    Color_codes[i] = Name;
                }
                else
                {
                    priority_file.close();
                    cout << "Error 2";
                    cin.get();
                    exit(EXIT_FAILURE);
                }
            }
        }
        else
        {
            clear_temporary_file(temp1.c_str(), temp1_cleared);
            for (int i = 0; i < COLORS; i++)
            {
                string Name;
                getline(priority_file, line);
                seperate_input(line, N, Name);
                if (N == (i+1)) 
                {
                    Name.pop_back();   //push last , out (I need it other function)
                    write_to_temporary_file(temp1.c_str(), Name);
                }
                else
                {
                    priority_file.close();
                    cout << "Error 2";
                    cin.get();
                    exit(EXIT_FAILURE);
                }
            }
        }

        priority_file.close();
    }
    void read_solution_and_generate_result(const char *filename)
    {
        ifstream solution_file(filename);

        if (solution_file == NULL) 
        {
            cout << "Error 3";
            cin.get();
            exit(EXIT_FAILURE);
        }

        string line;
        int N;

        for (int i = 0; i < LINES; i++)
        {
            string Other_stuff;
            getline(solution_file, line);
            seperate_input(line, N, Other_stuff);
            if (N == (i+1)) 
                Generate_values(i, Other_stuff);
            else
            {
                solution_file.close();
                cout << "Error 4";
                cin.get();
                exit(EXIT_FAILURE);
            }
        }

        solution_file.close();
    }
    void print_results_to_file(const char *filename)
    {
        ofstream result_file(filename);

        if (result_file == NULL) 
        {
            cout << "Error 5";
            cin.get();
            exit(EXIT_FAILURE);
        }

        if (!save_RAM)
        {
            for (int i = 0; i < COLORS; i++)
            {
                result_file << Color_codes[i];
                if (i != COLORS-1)
                    result_file << ",";
            }
        }
        else
        {
            for (int i = 0; i < COLORS; i++)
            {
                result_file << read_line(temp1.c_str(), i, false, 0, 0);
                if (i != COLORS-1)
                    result_file << ",";
            }
        }

        result_file << endl;

        if (!save_RAM)
        {
            for (int i = 0; i < LINES; i++)
            {
                for (int j = 0; j < COLORS; j++)
                {
                    if (Color_values[i][j] != "0")
                    {
                        result_file.setf(ios::fixed);
                        result_file << setprecision(9) << convert_to_double(Color_values[i][j]);
                        result_file.unsetf(ios::fixed);
                    }
                    else
                        result_file << convert_to_double(Color_values[i][j]);

                    if (j != COLORS-1)
                        result_file << ",";
                }
                result_file << endl;
            }
        }
        else
        {
            string value;
            for (int i = 0; i < LINES; i++)
            {
                for (int j = 0; j < COLORS; j++)
                {
                    value = read_line(temp2.c_str(), i, true, j, COLORS);
                    if (value != "0")
                    {
                        result_file.setf(ios::fixed);
                        result_file << setprecision(9) << convert_to_double(value);
                        result_file.unsetf(ios::fixed);
                    }
                    else
                        result_file << convert_to_double(value);

                    if (j != COLORS-1)
                        result_file << ",";
                }
                result_file << endl;
            }
        }

        result_file.close();
    }
};

int main() 
{
    bool save_my_RAM = false;

    Sorter sort(save_my_RAM);

    sort.get_user_input();
    sort.read_priority_file("priority.csv");
    sort.read_solution_and_generate_result("solution.txt");
    sort.print_results_to_file("results.txt");

    return 0;
}
Sign up to request clarification or add additional context in comments.

8 Comments

this sscanf(line,"%d,%s",&N,name); and this if (N == i) strcpy(Coul[i], name); (Edit: Sorry, my bad. I used wrong files. I'll try to fix/check this again.)
This code is quite hard on so many levels, so if you don't mind I will rewrite it in iostream and std libraries.
That would be great! it's a C style code, and I also have a hard time grasping it... THANKS!
Could you provide result file I should get? I also would like to wrap it in class, can I?
You have code 1 because exit(EXIT_FAILURE); was executed, try to find out where. Maybe filenames are wrong or something. Compiled it with Visual Studio 2012.
|
0

With the contents of the priority.csv file being:

1,PINK
2,Y2
3,Y4
4,Y6
5,CIN
6,K1
7,K2
8,OR0
9,PINKwA
10,PINKwB
11,MAGA
12,MAGB
13,MAGC
14,K2M
15,K1A
16,K1B
17,K1C
18,OR0A
19,OR0B
20,Y9
21,Y9A
22,gTUD
23,bTUD
24,TU
25,TUwA
26,TUwB
27,TUwC
28,REF
29,REFwA
30,REFwB
31,REFwC
32,XTwA
33,XTwB
34,XTwC
35,XTwD
36,GA
37,GB
38,GC
39,gY6A
40,gY6B
41,gY6C
42,gY6D
43,gY6E
44,gY2A
45,gY2B
46,gY2C
47,gY2D
48,gY2E
49,XTC1
50,XTC8II
51,XTC64II
52,XTC8
53,XTC64
54,XT
55,SBK
56,LBK
57,PAPER

This is the expected result:

PINK,Y2,Y4,Y6,CIN,K1,K2,OR0,PINKwA,PINKwB,MAGA,MAGB,MAGC,K2M,K1A,K1B,K1C,OR0A,OR0B,Y9,Y9A,gTUD,bTUD,TU,TUwA,TUwB,TUwC,REF,REFwA,REFwB,REFwC,XTwA,XTwB,XTwC,XTwD,GA,GB,GC,gY6A,gY6B,gY6C,gY6D,gY6E,gY2A,gY2B,gY2C,gY2D,gY2E,XTC1,XTC8II,XTC64II,XTC8,XTC64,XT,SBK,LBK,PAPER
0,0,0,0,0.624049619,0,0,0.369251239,0,0,0,0,0,0.003874916,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0.002824225,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
0,0,0,0,0.624372658,0,0,0.369683601,0,0,0,0,0,0.003651245,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0.002292496,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
0,0,0,0,0.624695697,0,0,0.370115963,0,0,0,0,0,0.003427574,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0.001760766,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
0,0,0,0,0.625018736,0,0,0.370548325,0,0,0,0,0,0.003203903,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0.001229036,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
0,0,0,0,0.625341775,0,0,0.370980687,0,0,0,0,0,0.002980232,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0.000697306,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
0,0,0,0,0.625664814,0,0,0.371413049,0,0,0,0,0,0.002756561,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0.000165576,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.