Converting from C++ to C

Hi, I'm working on a project, and below is a segment of my code written in C++. However, it's required in C, but I don't know how to write the counterpart of it in C. Also don't know if it's appropriate to ask question about C here, I'll delete it if so.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>

int main(int argc, char* argv[]) 
{	
	// Read in the data of Boolean function and variables prob.
	
	FILE *infile, *outfile;
	//ifstream infile;
	//ofstream outfile;
	
	stringstream ss;
	string line;
	
	string boolfunction;
	char var_name;
	float var_prob;
	
	int count = 0;

	// Construct a vector(list) which every element is a variable
	//which stores its name and probabilities
	vector<variable> var_list;
	

	// Open boolean function and variables prob. file 
	//infile.open("testcase/input1.txt", ios::in);
	infile = fopen(argv[1], "r");
	

	if(infile == NULL)
	{
		printf("Failed to open file! \n");
		exit(1);
	}
	
	outfile = fopen(argv[2], "w");
	
	
	
	infile >> boolfunction;
	while(getline(infile, line)) 
	{
		ss << line;
		while(ss >> var_name >> var_prob)
		{
			variable var;
			if(isupper(var_name))
			{
				//var.index = count-1;
				var.name = tolower(var_name);
				var.prob = 1 - var_prob;
				var.prob_not = var_prob;
				var_list.push_back(var);
			}
			else
			{
				//var.index = count-1;
				var.name = var_name;
				var.prob = var_prob;
				var.prob_not = 1 - var_prob;
				var_list.push_back(var);
			}
		}
		ss.str("");
		ss.clear();
		
		count++;
	}

return 0;
}


I've already modified some part of it, so it's now a hybrid of C & C++.
But some part like :
1
2
infile >> boolfunction;
	while(getline(infile, line)) 

Idk how to translate it.
Thx in advance!
Last edited on
somewhere along the way C added a getline.
so what the above says, is,
while there is data in the file
get a line

you can do that logic in C, but I am not sure what the correct loop condition is.

the file reading is done like reading from the console, fgets instead of gets or whatever it is. You just have to supply the file* instead of assuming its stdin.
start at the top and work through it, is my advice.
stringstream and string: c does not have, so you nee to mimic what you used from those tools.
Last edited on
Hello calvinforni,

I would start by posting the input file or a good sample, so everyone will know what you have to work with.

vector<variable> var_list; would become an array, but what is a "variable"? Are you missing a struct?

std::string would become a char array.

Not sure what to do with a string stream, but you may be able to do without it.

Your inner while loop may become the outer while loop replacing "ss" with "infile".

The code in the if/else would change to store the information in the array instead of the vector.

With out the input file that is as much as I see right now.

Andy
Hi, @Handy Andy
Yes, "variable" is a struct. I missed it in my code.
Here it is:
1
2
3
4
5
6
7
8
9
10
11
struct variable
{
	// The index of the variable
	int index;
	
	// The name of the variable
	char name;
	
	// Probability of the variable and its complement
	float prob, prob_not;
};

And the input file is as below:
ABcD+ABCD+aBcD+aBCD.
A 0.2
B 0.4
C 0.6
D 0.8

Thx for replying!
Last edited on
Hello calvinforni,

It took me awhile to figure this out, but here is a start:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>

#define MAXLIST 20
#define READLINE 51
#define BOOLFUNCSIZE 101

struct Variable
{
	char s_name;
	int s_index;
	float s_prob, s_prop_not;
};

int main(int argc, char* argv[])
{
	if (argc < 3)
	{
		printf("\n\n     Proper usage is:\n     (Progeam Name) (Input file) (Output File)");

		exit(1);
	}

	// Read in the data of Boolean function and variables prob.

	FILE* infile = { NULL };

	errno_t err = fopen_s(&infile, argv[1], "r");

	if (err)
	{
		printf("\n\n     The file \"%s\" was not opened\n", argv[1]);

		exit(2);
	}

	FILE* outfile = { NULL };

	err = fopen_s(&outfile, argv[2], "w");

	if (err)
	{
		printf("\n\n     The file \"%s\" was not opened\n", argv[2]);

		exit(3);
	}

	char line[READLINE] = { '\0' };
	char boolfunction[BOOLFUNCSIZE] = { '\0' };
	char var_name = { '\0' };
	int lineCount = { 0 };
	float var_prob = { 0.0 };


	// Construct an array(list) which every element is a variable
	//which stores its name and probabilities
	struct Variable var_list[MAXLIST] = { 0 };
	int var_list_used = { 0 };

	//lineCount = getline(&boolfunction, BOOLFUNCSIZE, infile);
	fgets(boolfunction, BOOLFUNCSIZE, infile);

	size_t idx = 0;
	char ch = { '\0' };

	while (idx < 4 && (var_list[idx].s_name = fgetc(infile)) != EOF)
	{
		fscanf_s(infile, "%f", &var_list[idx].s_prob);

		fgetc(infile);

		idx++;
	}
	return 0;
}

The 1st if statement in "main" is need to check what is available from the command line.

There are still some of the variables that need cleaned up and/or changed. Plus you need to keep track of how much of the array is used.

Andy
here the main question is how much of std::vector you will need to implement in C.
you can read this: https://www.reddit.com/r/C_Programming/comments/389cq2/c_vector_in_c/

if you don't need vector functionality(i.e. random access etc.) then you can store 'variable' in a linked-list.
and stream is just being used to parse, which can be done with atoi / atof and various c-string statements. You don't need to re-create it, you just need to do what it did. Same for vector, you don't have to re-create the whole thing
honestly
struct vec
{ type* tp; unsigned int size; unsigned int capacity;}; //this will do 90% of what you need where type is double or int or another struct ... whatever. you can use void * to make it generic if you want to go there, but that is more ugly than useful most of the time. a void* and an enum to tell it what type it is would be reasonable if you hide the void* from everything outside the struct and its immediate 'methods' (which are not like c++ they would just be free functions). You actually can add methods with function pointers, but here again, is it worth it?

^^^ while you can do some other data structure, I can't see how coding up a list is easier than just a single pointer allocation which acts like a vector / array 'naturally'.
Last edited on
>
^^^ while you can do some other data structure, I can't see how coding up a list is easier than just a single pointer allocation which acts like a vector / array 'naturally'.


did you meant to me? well, then you may need dynamically allocated "auto resizing" array. because input file may not be fixed sized.

edit: its possible without "auto resizing" array. count total object numbers from the input file & create array of that size.

Last edited on
edit: its possible without "auto resizing" array. count total object numbers from the input file & create array of that size.


yes, this. There are always a few edge cases where you can't find out how many for some reason, but C has realloc! Much like a vector, it would be wise to call this sparingly, getting a lot of items every time you run out -- that is why my little vector light struct had a capacity field. So even if you cannot count the input (say it is typed in by user) ... you can manage with a tiny bit of code rather than write a list. And the list idea isn't "bad" (I was not trying to imply this) if you need the functionality, its just a lot more work if its a small program being converted.
Last edited on
Another alternative to possibly simply the code is to process the file twice - first pass determine how many lines/variables there are and then allocate the required memory (calloc). Then a second pass to parse and extract. Its a small file so the performance difference won't be noticeable. This means there's no need to code a list/vector replacement or bother with realloc() et al.

Topic archived. No new replies allowed.