Solved

Trying to add a character and strings to a char array or char * in C but failing.

Posted on 2013-01-31
13
624 Views
Last Modified: 2013-02-01
Hi there;

I have several problems

1) expanding an char array (or should I expand)
2) I am trying to add a character to a string value. It's straight forward but I fail.

# include <stdio.h>
# include <string.h>
# include <time.h>
# include <stdlib.h>
char * construct();

void main()
{	
	int filesize = 50000;	
	int bufflen = 50 * 1024;
	int strsize;
	char * buffer = new char[bufflen];	
	char *randstr = construct();

	*buffer = '\0';
	
	strsize = strlen(randstr);
	int actual;
	while (bufflen >= 0) {
		strcat(buffer, randstr);
		actual = bufflen;
		bufflen -= strsize;  
		if(bufflen <= 0)  
			break;

	}
	bufflen = actual;
	FILE *pfile = fopen("bigfile.txt","wt");
	for(int i=0; i < filesize/bufflen;i++)
	{
		fwrite(buffer, 1, bufflen, pfile);
	}
	fclose(pfile);
}

char randCharacter()
{
	char randChar = ' ';
	int counter = 0;
	int randNum = 0;

	// Provide seed for the random number
	// generator.
	srand(time(NULL));
	//for (counter = 0; counter < 10; counter++)
	{
		// First, pick a number between 0 and 
		// 25.
		randNum = 26 * (rand() / (RAND_MAX + 1.0));

		// The ASCII code for 'A' is 65, so
		// add 97 to the random number to get
		// a lower case letter.
		randNum = randNum + 65;

		// Type cast to character to convert
		// it to a char type.
		randChar = (char) randNum;

	}
	//printf ("Random char: %s\n", randChar);
	return randChar;
}


char * construct()
{		
	char randstr[20] = "ABCDEFGHIJ";
	
	strcat(randstr, "X"); //Actually planning to append a char first, from randCharacter function

	printf("Rand:%s\n", randstr);
	printf("Len: %d\n", strlen(randstr));
	printf("ten: %c\n", randstr[10]);
//Outputs correctly in console but writes the first 6 to the file.

	//strcat(randstr, "12 1.5\n"); Int and double values are actually dynamically generated
	//strcat(randstr, "43 1.8\n");
	
	return randstr;
}

Open in new window


This question is a linked question:
http://www.experts-exchange.com/Programming/Languages/C/Q_28013850.html

Regards.
0
Comment
Question by:jazzIIIlove
  • 6
  • 4
  • 3
13 Comments
 
LVL 51

Assisted Solution

by:Julian Hansen
Julian Hansen earned 100 total points
ID: 38841611
Firstly I would use the following to generate your random upper case char.
char c = (char)((rand() % 26) + 65);

Open in new window


Other than that - not sure where it is failing - what does it do that it shouldn't or not do that it should
0
 
LVL 84

Assisted Solution

by:ozo
ozo earned 400 total points
ID: 38841617
Did you notice any error messages when you tried to compile it?

try changing

 char * buffer = malloc(bufflen);


        static char randstr[20] = "ABCDEFGHIJ";
0
 
LVL 12

Author Comment

by:jazzIIIlove
ID: 38841793
ok, my mistake. The question wasn't clear. It's running, no compile errors. but what I actually need is:

i am using strcat to concatanate "ABCDEFGHIJ". i cannot concatanate a char 'X', so i think i need to convert and concat.
char c = (char)((rand() % 26) + 65); //credit to : julianH.

strcat(randstr, "X"); //Actually planning to append a char---> not a string char.


My other actual problem is in the comments:
//strcat(randstr, "12 1.5\n"); Int and double values are actually dynamically generated
//strcat(randstr, "43 1.8\n");

randstr has an original value, now added a character and now I need expand the randstr more to add the int and float looking values. What is the elegant way of doing this?

Regards.
0
 
LVL 84

Assisted Solution

by:ozo
ozo earned 400 total points
ID: 38841835
You should have gotten an error about 'new' being undeclared, if not a warning about returning the address of local variable.

But after those are fixed,

You subtract a strsize of 11 from a bufflen of 51200
4654 times, leaving a bufflen = actual of 6,
so each
    fwrite(buffer, 1, bufflen, pfile);
only writes 6 bytes at a time.
0
 
LVL 12

Author Comment

by:jazzIIIlove
ID: 38841916
Hi;

I am trying to form a big file with a pattern. I really don't get an error in new part, but failed to concat a char as a char to a string since randstr[20] is fixed, it should be expanding as I am not only planning to concat a char but also other strings to form the file content but failed.


void main()
{	
	int filesize = 50000;	
	int bufflen = 50 * 1024;
	int strsize;
	char * buffer = new char[bufflen];	
	char *randstr = construct();

	*buffer = '\0';
	
	strsize = strlen(randstr);
	int actual;
	
	while (bufflen >= 0) {
		strcat(buffer, randstr);
		actual = bufflen;
		bufflen -= strsize;  
		if(bufflen <= 0)  
			break;
	}

	bufflen = actual;
	
	FILE *pfile = fopen("bigfile.txt","wt");
	for(int i=0; i < filesize/bufflen;i++)
	{
		fwrite(buffer, 1, strlen(randstr), pfile);
	}
	fclose(pfile);
}


char * construct()
{		
	char randstr[20] = "ABCDEFGHIJ";
	
	char c = (char)((rand() % 26) + 65);

	strcat(randstr, "X"); //Actually planning to append a char first, from randCharacter function

	printf("Rand:%s\n", randstr);
	printf("Len: %d\n", strlen(randstr));
	printf("ten: %c\n", randstr[10]);
//Outputs correctly in console but writes the first 6 to the file.

	//strcat(randstr, "12 1.5\n"); Int and double values are actually dynamically generated
	//strcat(randstr, "43 1.8\n");
	
	return randstr;
}

Open in new window


Regards.
0
 
LVL 12

Author Comment

by:jazzIIIlove
ID: 38842271
Hi;

Here is my finalized code. I have stuck currently in the idea of outer loop of construct() function. If I don't use a loop I can print out but I need loop over alphabet letters.

I also tried to call the function in a loop, but then the buffer construction is lost. Following is the final complete code:

# include <stdio.h>
# include <string.h>
# include <time.h>
# include <stdlib.h>
# include <math.h>
char * construct();

void main()
{	
	int filesize = 50000;	
	int bufflen = 50 * 1024;
	int strsize;
	char * buffer = new char[bufflen];
	char *randstr = construct();

	*buffer = '\0';

	strsize = strlen(randstr);
	int actual;

	while (bufflen >= 0) {
		strcat(buffer, randstr);
		actual = bufflen;
		bufflen -= strsize;  
		if(bufflen <= 0)  
			break;
	}

	bufflen = actual;

	FILE *pfile = fopen("bigfile.txt","wt");
	for(int i=0; i < filesize/bufflen;i++)
	{
		fwrite(buffer, 1, strlen(randstr), pfile);
	}
	fclose(pfile);
}

double truncateDouble(double x, int digits)
{
	double f=pow(10.0, digits);
	return ((int)(x*f))/f;
}

char * construct()
{		
	
	static char randstr [1000000] = "Operator ";
	srand(time(NULL));
	for(int m = 65; m <=90; m++)
	{				
		//char c = (char)((rand() % 26) + 65);
		char c =m++;
		randstr[9] = c;
		randstr[10] = ':';
		randstr[11] = '\n';

		
		int j = 0;
		int r[50];
		double p[50];
		double tr[50];
		for(int i = 1000; i < 20000; i+=1000)
		{
			r[j] = rand() % i + 10;
			p[j] = ((double)(rand() % i)/(double)RAND_MAX+rand() % (j+1));	 

			char integer_string[32];
			sprintf(integer_string, "%d", r[j]);

			char double_string[32];
			sprintf(double_string, "%.2f", p[j]);

			strcat(randstr, integer_string);
			strcat(randstr, " \t");
			strcat(randstr, double_string);
			strcat(randstr, "\n");
			j++;
		}
		strcat(randstr, "\n");										
	}	
	strcat(randstr, "\0");										
	return randstr;
}

Open in new window

0
Highfive Gives IT Their Time Back

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

 
LVL 12

Author Comment

by:jazzIIIlove
ID: 38842452
Hi;

I made the code finally working but I am afraid the code quality sucks..Can anyone inform me what to do to make this code better?

My aim is to populate the file to a huge size within the
for(int i = 0; i < filesize/100;i++)

Open in new window

loop. This is also related with the question link in this question.

# include <stdio.h>
# include <string.h>
# include <time.h>
# include <stdlib.h>
# include <math.h>
# define filesize 50000

char * construct(char c, int bufflen);

void main()
{		
	int strsize;

	FILE *pfile = fopen("bigfile.txt","wt");		 
	int m = 65;
	srand(time(NULL));
	for(int i = 65; i <= 90;i++)
	{
		int bufflen = 50 * 1024;	
		char * buffer = new char[bufflen];
		*buffer = '\0';
		char * randstr = construct(i, bufflen);
		strsize = strlen(randstr);

		bufflen = strsize;	
		fwrite(randstr, 1, bufflen, pfile);

	}
	fclose(pfile);
}

char * construct(char c,int bufflen)
{		
	char randstr[1000000] = "Operator ";	

	randstr[9] = c;
	strcat(randstr,":\n");

	for(int i = 0; i < filesize/100;i++)
	{
		int j = 0;
		int r[50];
		double p[50];
		double tr[50];
		for(int i = 1000; i < 20000; i+=1000){
			r[j] = rand() % i + 10;
			p[j] = ((double)(rand() % i)/(double)RAND_MAX+rand() % (j+1));	 	

			char integer_string[32];
			sprintf(integer_string, "%d", r[j]);

			char double_string[32];
			sprintf(double_string, "%.2f", p[j]);
			strcat(randstr, integer_string);
			strcat(randstr, " \t");
			strcat(randstr, double_string);
			strcat(randstr, "\n");
			j++;
		}	
	}
	return randstr;
}

Open in new window


Regards.
0
 
LVL 84

Accepted Solution

by:
ozo earned 400 total points
ID: 38842564
One problem is that your construct function is still returning the address of a local variable.
to avoid undefined behaviour, you should make randstr static, or else allocate it.
0
 
LVL 51

Expert Comment

by:Julian Hansen
ID: 38842687
Suggestion - close one of your questions and focus on the other - essentially they are focusing on the same thing.
0
 
LVL 84

Assisted Solution

by:ozo
ozo earned 400 total points
ID: 38842783
It is not clear why r and p should be arrays, nor what tr is for.
And what's the purpose of
int m = 65;
or of
 bufflen = strsize;

and why is bufflen passed to construct?
0
 
LVL 51

Expert Comment

by:Julian Hansen
ID: 38843339
I think the above are legacy hold overs from a progessive journey of discovery.

I asked similar questions in the other post - hence the suggestion the two be combined - duplicating effort here.
0
 
LVL 12

Author Comment

by:jazzIIIlove
ID: 38843433
:/

Terribly sorry, actually i didn't mean to duplicate but it really looks like a duplication.

Ok I grade the most of points to you for other question, and most of points here to Ozo.

Regards.
0
 
LVL 12

Author Comment

by:jazzIIIlove
ID: 38843436
Ozo, let's continue from the other question.

Regards.
0

Featured Post

How to improve team productivity

Quip adds documents, spreadsheets, and tasklists to your Slack experience
- Elevate ideas to Quip docs
- Share Quip docs in Slack
- Get notified of changes to your docs
- Available on iOS/Android/Desktop/Web
- Online/Offline

Join & Write a Comment

Have you thought about creating an iPhone application (app), but didn't even know where to get started? Here's how: ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ Important pre-programming comments: I’ve never tri…
This is a short and sweet, but (hopefully) to the point article. There seems to be some fundamental misunderstanding about the function prototype for the "main" function in C and C++, more specifically what type this function should return. I see so…
The goal of this video is to provide viewers with basic examples to understand how to use strings and some functions related to them in the C programming language.
Video by: Grant
The goal of this video is to provide viewers with basic examples to understand and use for-loops in the C programming language.

746 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

9 Experts available now in Live!

Get 1:1 Help Now