ahamed101 40 Junior Poster

So what is your doubt anyway... :D

"I was wondering if realloc() copied the contents of the block of memory to the new block"... The answer is NO... realloc only increases the size of the previously allocated memory...

ahamed101 40 Junior Poster

Good Job!!!... Please let us know if it was a technical error or logical... if technical, give us a brief note about it...

ahamed101 40 Junior Poster

fgets is always safe... cause in fgets we can specify the size of the string that should be read... in such a case we can be sure only the specified no of bytes will be read...

gets is not like that... it will read whatever we give and may overwrite the memory locations not allocated for that particular string variable...


eg:

char acName[20];

/* Using fgets */
fgets(acName, 20, stdin);

/* Using gets */
gets(acName);

For the first one using fgets, even if we give any string greater than 20 in length, it will accept only 20.... but in gets if we give string of length 30, it will accept all the 30 and over write the memory locations not allocated for acName...


Hope it clears your doubt...

ahamed101 40 Junior Poster

Also, argv is of type char**... so use strcmp to compare the strings...

ahamed101 40 Junior Poster

To improve the code...

You are using STRUCT_SIZE (which is #defined to probably the max no of records) in the for loop... if the no of records in the text file is not equal to STRUCT_SIZE, then for loop, simply loops unnecessarily... So find the no of records and then use that count for the loop...

If you are using a structure to write/read to/from a file, then use fread and fwrite... these functions come more handy... when you write, just populate the structure and write it... and when you read just pass the structure, it will read from the file and assign the values to the proper structure variables... so you dont need to use scanf, fscanf etc and can avoid errors in using the format specifier...

eg:

typedef struct _employee{
	int iNum;
	char acName[20];
}Employee, *Employee;
#define SIZEOFEMP sizeof(Employee)

...

FILE *pFile;
Employee sEmpStr;
sEmpStr.iNum = 10;
strcpy(sEmpStr.acName, "Ahamed");

/* Writing */
pFile = fopen("myfile.txt","a+");
if(pFile != NULL){
        /* You might want to check the return value of fwrite for robust code */
	fwrite(&(sEmpStr),SIZEOFEMP,1,pFile);
	fclose(pFile);
}
else{
	printf("\n Could not open file for writing...");
	return 1;
}

...

/* Reading from the file */
pFile = fopen("myfile.txt","r");
if(pFile != NULL){
        /* You might want to check the return value of fread for robust code */
	fread(&(sEmpStr),SIZEOFEMP,1,pFile);
	fclose(pFile);
}
else{
	printf("\n Could not open file for reading...");
	return 1;
}
/* Print the calues directly */
printf("\n Number : %d",sEmpStr.iNum);
printf("\n Name   : %s",sEmpStr.acName);

...
ahamed101 40 Junior Poster

You are missing the "i" increment in the while loop...

while(loop!=EOF)
	{
		printf("%s %s %s %s %d\n",factory_info[i].machine,factory_info[i].employee,factory_info[i].date,
factory_info[i].test_value,factory_info[i].qualification_rate);

/* You must increment i */
i++;

		loop = fscanf(data_txt,"%s" "%s" "%s" "%s" "%d",factory_info[i].machine,factory_info[i].employee,factory_info[i].date,
factory_info[i].test_value,&factory_info[i].qualification_rate);
	}
ahamed101 40 Junior Poster

Please mark the thread as solved...
Thank You...

ahamed101 40 Junior Poster

scanf_s is some kind of secure version of scanf... its available in msdn...

ahamed101 40 Junior Poster

the function name is different... the prototype has celsiusAtDepth and the definition has celsiusAtdepth...

float celsiusAtDepth (float);

float celsiusAtdepth ( float depth)
ahamed101 40 Junior Poster

Please mark the thread as Solved...
Thank You...

ahamed101 40 Junior Poster

what is the series all about... is there any general formula for this?... give an example... like if n =3, output should be?...

ahamed101 40 Junior Poster

this is wrong... you are missing one "%d"

scanf("%d",&a,&b);

corrected code

scanf("%d %d",&a,&b);

This is also wrong...

printf("d%d,a,b\n");

Corrected code

printf("%d %d\n",a,b);
ahamed101 40 Junior Poster

Try this...

switch(){
   case 1: 
               ;bool aaaa;
               break;
   ...
   ...
}

This will not give any error...

ahamed101 40 Junior Poster

what is the error that you are getting?...

ahamed101 40 Junior Poster

Move the for loop to the function you want... like...

int sum(int n){
int i = 0;
int total = 0;
int sum = 1;
	for(i=1; i<n; i++)
	{
		sum = sum + 3;
		total = total+sum;
	}
total++;

return total;

}

int main(int argc, char **argv)
{
	int i;
	int n;
	int sum = 1;
	int total = 0;
 
	printf("\n Please enter a positive integer : ");
	scanf("%d",&n);
	if(n <= 0){
		printf("\n Error!!!");
		return 1;
	}

total = sum(n);
	printf("\n Total %d",total);
	getchar();
	return 0;
}
ahamed101 40 Junior Poster

Hi,
There are standard functions for all the ones you have said above... check out math.h...
What kind of idea are you expecting anyways?...
For add, you need to have atleast 2 numbers... take number 1, take number 2, add them... thats all...

Be specific about what you want...

ahamed101 40 Junior Poster

Hi,
this code is tooooo big to analyse... tell us whats the issue you are facing(be specific) so that we can help you...

ahamed101 40 Junior Poster

>You need to flush the input buffer before you get the next input...
What if there's nothing to flush from the buffer before input?

I said, we need to flush the input before getting the next input... of course the programmer would know when is the next input...

> while((ch = getc(stdin)) != EOF && ch != '\n'); What's more likely to occur first, the END OF FILE or the ENTER key?

Good question... probably, anything can halt this loop... and probably clear the input stream...

> scanf("%c", &operation); I think it is time for you to start learning how to check the return of scanf().
Better yet. Outgrow that function.

Yes, we should check the return value of scanf for a robust code... but here i was just pointing out his mistakes...

ahamed101 40 Junior Poster

Yes it would do what you want... here just modified it to enable it for the user to enter the value...

int main(int argc, char **argv)
{
	int i;
	int n;
	int sum = 1;
	int total = 0;

	printf("\n Please enter a positive integer : ");
	scanf("%d",&n);
	if(n <= 0){
		printf("\n Error!!!");
		return 1;
	}

	for(i=1; i<n; i++)
	{
		sum = sum + 3;
		total = total+sum;
	}
	total++;/* To take care of 1 */
	printf("\n Total %d",total);
	getchar();
	return 0;
}
ahamed101 40 Junior Poster

You should not give that space at the end...

scanf("%d %d %d %d", &a1,&a2, &a3, &a4);
ahamed101 40 Junior Poster

In your search function, you are just opening the file... you are not reading from it... without reading you are searching...

ahamed101 40 Junior Poster

Hi,
When I used scanf instead of scanf_s, it printed the output properly... I am not aware of scanf_s... googled it and found it out its some secure version of scanf or something... i use unix and this is available only for MS C I guess...

scanf("%d %d %d %d ", &a1,&a2, &a3, &a4);
ahamed101 40 Junior Poster

You need to flush the input buffer before you get the next input...

...
	printf("\n ENTER OPERATOR SIGN : ");
	char ch;
	while((ch = getc(stdin)) != EOF && ch != '\n');
	scanf("%c", &operation);
...

And you are missing %d, add that else you will not get the answer...

printf("\n Answer = %d", firstNumber + secondNumber);

And like Narue said, its %c and not %ch...

ahamed101 40 Junior Poster

Yes that helps...

int main(int argc, char **argv)
{
	int i;
	int n = 3;
	int sum = 1;
	int total = 0;

	for(i=1; i<n; i++)
	{
		sum = sum + 3;
		total = total+sum;
	}
	total++;/* To take care of 1 */
	printf("\n Total %d",total);
	getchar();
	return 0;
}

Let me know if its work...

WaltP commented: Solving someone's homework for them -3
ahamed101 40 Junior Poster

Nope this loop doesn't go to infinity...
For positive and negative value of both i and j, it will not even enter the loop...
if either i or j is negative, it will enter the loop once... thats it...

ahamed101 40 Junior Poster

Use continue instead so that you can enter the salary again...

i = 1;
	while(i <= numb_salaries){

		printf("Enter salary #%i: ",i);
		scanf ("%i", &salary);
		if(salary < 0){
			printf("\n Please enter a valid salary...\n Press enter to re-try...");
			fflush(NULL);
			getchar();
			continue;
		}
		sal_total = sal_total + salary;
		i++;
	}
ahamed101 40 Junior Poster

Hi

I am working on a program that computes the sum of N in increments of 3. I do not have any errors but when you run the program it does not compute correctly for example if you enter 2 for n the sum should be 5

#include "stdafx.h"
#include "stdio.h"

int
main(void)
{
int n, i, sum;
sum = 1;
printf(" Please enter a positive number\n");
scanf("%d", &n);
for(i=0; i<=n; i++);
{sum+=i;
}
printf("sum is %d", sum);
	  

	return 0;
}

You know what... we didn't get your question correctly... you said if the input is 2, output should be 5... it simply means you have to add 3 to n, n+3=output... is this what you want?
Or like you said increments of 3, as in... you give 2 out put should be (1+3)+(2+3)=9. if n is the input then (1+3)+(2+3)+(3+3)+(4+3)+(5+3)...+(n+3)=output, is this what you want?... Post the formula so that we can help you...

ahamed101 40 Junior Poster

Strings are passed by reference by default...
atoi-> Like salem said error handling is bit tough...
sscanf-> is what i would have used, it would separate as well as convert it to int format(or what ever format)...
strtol->Parses the C string str interpreting its content as an integral number of the specified base, which is returned as a long int value
long int strtol ( const char * str, char ** endptr, int base );

ahamed101 40 Junior Poster

fflush(stdin) is commonly used by everyone in their code to flush the input stream... even i was also using that until Salem and some others from this group corrected me... fflush(stdin) will work most of the time but it is not all recommended to use that... if you want to flush the input stream, do it manually...

while((ch = getchar()) != '\n');

This should do the trick of clearing the input stream...

ahamed101 40 Junior Poster

You can read and write simultaneously like Sci@phy suggested...

1. Open file 1 in read mode
2. Open file 2 in append mode
3. read from file 1
4. do the processing
5. write to file 2
6. continue from step 3 till end of file of file 1
7. close file 2
8. close file 1

ahamed101 40 Junior Poster

Here's another redirection
http://cboard.cprogramming.com/showthread.php?t=107852

That Rocked!!!

ahamed101 40 Junior Poster

Hi,
Its all done wrong, have given the comments inside...

#include <stdio.h>                 /*Include the standard I/0 header file */
#include <string.h>                /*Include the standard I/0 header file string library */
 
//The functions that are meant to be defined
char* toPLString(char * inputstring); 
int getInputBygetChar(char input[]);
int getInputByfgets(char input[]);
int getInputByscanf(char input[]);
 
 
int main(int argc, char *argv[]){
    char phrase[1000];
    char *token;

/* Calling this function getInputByscanf will not get you back the string read from that function. The function call is wrong, the argument is missing */

printf("%s", getInputByscanf);

    printf("The sentence in Pig Latin is: ");

/* You are trying to strtok the string phrase[] which has nothing in it at this point */

token = strtok(phrase, " ");
    toPLString(token);
    printf("\n");
 
    system("Pause");
    return 0;
}
//method to convert to Pig Latin
char* toPLString(char * inputstring){
     char *toPLString = inputstring;
     while (toPLString != NULL){
           printf("%s%c%s", toPLString + 1, toPLString[0], "ay ");
           toPLString = strtok(NULL, " ");
           printf(" ");
     }
}
 
//Method to to read a string from keyboard and return number of characters read.
getInputBygetChar(char input[]){
 
}
 
//Method that uses the fgets method to read a string from keyboard and return number of characters read.
int getInputByfgets(char input[]){
 
}
 
/*Method that uses the scanf method to read a string from keyboard and return number of characters read.
*Scanf reads a character string. The scan terminates at whitespace. A null character is stored at the end
of the string. However, the input string size from a user is arbitrary.*/ …
ahamed101 40 Junior Poster

How about a Scientific Calculator?

ahamed101 40 Junior Poster

Hi,
Please be more specific... What is it that you are looking for? If you want the program to prompt the user to enter the Standing charger and Rate per unit, then you can do it just the way you are taking previous and present readings.

ahamed101 40 Junior Poster

Hi,
Please be more specific...
First of all, use code tags when you put up the code...
Secondly, whats the actual issue?... Did you mean it runs only once even if you select Sign Up? or is it taking only Username and Password?

Tips : Clear the input buffer before you take in the next input.

Clearer the question, quicker it will get replies...

ahamed101 40 Junior Poster

Hi All,

newt.c_cc[VMIN] = 1;
newt.c_cc[VTIME] = 0;

need to set this... it worked and thanks a lot to frk who helped me in this...

Salem commented: Well done, and thanks for the update for the solution. +22
ahamed101 40 Junior Poster

Hi Salem,
I am using HP-UX machine...
Yes I am searching other forums also, nothing helps... Hope to get around this somehow...

ahamed101 40 Junior Poster

Thanks very much for ur helps but sorry ... I don't get what u mean. I m just a beginner. Here I removed function and tested, it run, compiled but error with result.
What should I do? Thanks anyway.

#include <stdio.h>
int main( )
{
	struct student
		{
			char name;
			char dep;
			char course;
			int roll;
			int year;
		};
	struct student d2[3];
	int i;
	printf("Enter Roll Number,Name, Department, Course, Year of Joining\n");
	for (i=0;i<=2;i++){
			scanf("%d %c %c %c %d",&d2[i].roll,&d2[i].name,&d2[i].dep,&d2[i].course,&d2[i].year);
		}
	for (i=0;i<=2;i++)
		printf("\nRoll Number:%d Name:%c Department:%c Course:%c Year of Joining:%d",d2[i].roll,d2[i].name,d2[i].dep,d2[i].course,d2[i].year);
	return 0;
}

Is it resolved?

ahamed101 40 Junior Poster

Guys, any suggestions?

ahamed101 40 Junior Poster

I have been programming in C for many years, but I have just started using GCC/Eclipse for a new project to develop a product using an embedded ARM processor. I have found a problem that hasn't existed in previous C compilers I have used:

I have created a define as follows:

#define SWS pRCC->CFGR, B2+B3, 2
#define ReadPeriph(Address, Bits, Shift) ((Address & (Bits)) >> Shift)

If in my code I insert two lines:

x8 = ReadPeriph(sRCC->CFGR, B2+B3, 2);
y8 = ReadPeriph(SWS);

I would expect both lines to compile correctly and give the same result. However, although the first line is OK, the compiler generates an errors on the second saying "Multiple markers at this line - 'ReadPeriph' undeclared (first use in this function)

Hi there,

You have defined the macro incorrectly. The second part should not have any spaces.

Wrong macro definition

#define	SWS		pRCC->CFGR, B2+B3, 2

Correct macro definition

#define	SWS		(pRCC->CFGR,B2+B3,2)

Try this and let me know if it works...
And one more thing, GCC is always correct... :)

ahamed101 40 Junior Poster

I tried flushing the outpur stream... but no luck... I still need to press enter thrice... i did a gdb and found out that at this line ch = getchar() the program waits for extra two more enter to be pressed...

Is there something to do with the terminal settings?... I tried this in FreeBSD, its working fine... but in HP-UX, AIX its not and it is there where I want to use...

ahamed101 40 Junior Poster

Hi,
Please find the code snippet...

#include <stdio.h>
#include <termios.h>
#include <unistd.h>

int mygetch ( void )
{
  int ch;
  struct termios oldt, newt;

  tcgetattr ( STDIN_FILENO, &oldt );
  newt = oldt;
  newt.c_lflag &= ~( ICANON | ECHO );
  tcsetattr ( STDIN_FILENO, TCSANOW, &newt );
  ch = getchar();
  tcsetattr ( STDIN_FILENO, TCSANOW, &oldt );

  return ch;
}

int main()
{
	char ch;

	ch = mygetch();

	printf("\n Entered Character : %c",ch);

	return EXIT_SUCCESS;
}

I have to press enter twice only then the character gets printed.
One more instance...

#include <stdio.h>
#include <termios.h>
#include <unistd.h>

int mygetch ( void )
{
  int ch;
  struct termios oldt, newt;

  tcgetattr ( STDIN_FILENO, &oldt );
  newt = oldt;
  newt.c_lflag &= ~( ICANON | ECHO );
  tcsetattr ( STDIN_FILENO, TCSANOW, &newt );
  ch = getchar();
  tcsetattr ( STDIN_FILENO, TCSANOW, &oldt );

  return ch;
}

int main()
{
	char ch;

	printf("\n Hello World");
	printf("\n Press any key to continue...");
	mygetch();

	return EXIT_SUCCESS;
}

Here also I need to press enter twice only then the second message gets displayed "Press any key to continue..."

Platform : HP-UX

Any suggestions would be of great help...

Thank You

ahamed101 40 Junior Poster

Hi Everyone,

I know conio.h is not available in Unix. I want to use getch(). Using curses.h needs causes the screen to clear which I don't want.

I found a code snippet (source : internet) using termios, it works, the thing is I need to press enter/or any other key thrice...

#include <stdio.h>
#include <termios.h>
#include <unistd.h>

int mygetch ( void ) 
{
  int ch;
  struct termios oldt, newt;
  
  tcgetattr ( STDIN_FILENO, &oldt );
  newt = oldt;
  newt.c_lflag &= ~( ICANON | ECHO );
  tcsetattr ( STDIN_FILENO, TCSANOW, &newt );
  ch = getchar();
  tcsetattr ( STDIN_FILENO, TCSANOW, &oldt );
  
  return ch;
}

Any help on this would be of great help...

ahamed101 40 Junior Poster

Why the hell would you cast the malloc. You shouldn't do that! Read this.

@OP for me most of of the things seems to be fine, except the head node pointer deferenceing like it has been mentioned by others already. Unless you've got your head node like this

void Insert( NODE **h, data );

???

ssharish

Thanks for that info... i wasn't aware of that...

ahamed101 40 Junior Poster

how could I add something to the function so it calculates when and if n is negative

Yeah, negative factorial is wrong, why do you want that anyways?...

ahamed101 40 Junior Poster

Hi ArkM,
How else can we clear the input stream?... I think the issue with the above code is basically the input stream is not cleared... I also read that the usage of fflush for stdin is undefined...


Regards,
Ahamed

ahamed101 40 Junior Poster

Hi there,
Other than the syntax error, there is no issue with the logic... Below I am pasting the correct code with a print statement...

#include "conio.h"
#include "stdio.h"

int fib (int n); // function prototype//

int main (void)

{
	int num, result;
	printf ("Please enter a positive integer\n");
	scanf ("%d", &num);
	result= fib (num);
	printf("\n Fib : %d",result);
	getch();
	return (0);
}
int fib (int n)
{

	if ((n == 0) || (n == 1)) // stopping cases
	return 1;
	else // recursive case
	return fib(n-1) + fib(n - 2);
}
ahamed101 40 Junior Poster

Hi there,

for (i=0;i<=2;i++){
		fflush(stdin);
			scanf("%d %c %c %c %d",&d2[i].roll,&d2[i].name,&d2[i].dep,&d2[i].course,&d2[i].year);
		}

Just add fflush(stdin) inside the for loop... this will solve your problem...
To remember : Always use fflush(stdin) before scanf() cause if not done, the input which you have given will remain in the input stream and it will get read by scanf next time...

Salem commented: Stop recommending fflush(stdin). It's just plain wrong. -4
ahamed101 40 Junior Poster

Hi,
If its ok the character is echoed on the screen, you can very well go for getc(stdin) or getchar() in a while loop with the termminating condition like carriage return or something you want...

ahamed101 40 Junior Poster

Hi,
I am not able to run the program in Windows using Eclipse, it give me error...
To get more info on core file, comile your sources with -g option like
cc P3.c -c -g P3.o
and then when the core is generated run the command
gdb a.out core
It will give you the details as in where the segmentation fault occured... You may want to use where command when in gdb mode...

Will analyse your code and let you know whats the issue...