how to store integer number into a character pointer in c - c

I am trying to store character as well as integer numbers in the same region through character pointer however, I am not getting the intended result. It is displaying only characters.
Here, I have created a character pointer which should contain atleast both characters and
integers, then should display them properly.
int main()
{
char c,store[30];
char *p=malloc(30);
int choice,i=0,n;
p=store;
while(1)
{
printf("\n********Menu**********");
printf("\n1.Enter a character");
printf("\n2.Enter a Number");
printf("\n3.Enter a double");
printf("\n4.Display the values");
printf("\n0.Exit");
printf("\nEnter your choice:");
scanf("%d",&choice);
switch(choice)
{
case 1:
printf("\nEnter a character:");
fflush(stdin);
scanf("%c",&c);
*p=c;
p++;
break;
case 2:
printf("\nEnter a Number");
scanf("%d",&n);
*p++=n;
break;
case 4:
*p--='\0';
for(i=0;store[i];i++)
printf("%c",store[i]);
break;
case 0:
exit(0);
break;
}
}
getch();
return 0;
}

You can't simply write doubles and int into a char array.
However with following you could see 0-9 :
case 2:
printf("\nEnter a Number"); //Just for 0-9
scanf("%d",&n);
*p=n+48; //Convert to ascii
p++;
break;

Related

C Program, Array inside a case in continuous Switch Menu loop

My array inside case 4 in looping Switch Menu doesn't print/display the value of the last array when the user input goes beyond array[4].
I tried to take the case 4 out and make it a single program to check if it doesn't really work on its own but it works fine, but when I put it back into the Switch, same issue again. I thought that maybe the initialization part is the problem. Help
`
#include <stdio.h>
int main ()
{
char first[20],last[20];
float math,eng,sci,avg;
int a,b,c,d,diff,array[diff],e,i,input;
do{
printf("\nMAIN MENU\n");
printf("[1] Basic Input Output\n[2] Conditional Statement\n[3] Looping Construct\n[4] Array\n[5] About\n[6] Exit");
printf("\n\nChoose: ");
scanf("%d",&input);
printf("\n");
switch (input)
{
case 1:
printf("\nEnter your given name:");
scanf("%s",first);
printf("Enter your surname:");
scanf("%s",last);
printf("\nHello %s %s!\n",first,last);
break;
case 2:
printf("\nEnter your grade in Math:");
scanf("%f",&math);
printf("\nEnter your grade in Science:");
scanf("%f",&sci);
printf("\nEnter your grade in English:");
scanf("%f",&eng);
avg=(math+eng+sci)/3;
if(math>eng&&sci)
{
printf("\nHighest grade is in: Math");
}
if(eng>math&&sci)
{
printf("\nHighest grade is in: English");
}
if(sci>eng&&math)
{
printf("\nHighest grade is in: Science");
}
if(math==eng)
{
printf("\n--Math and English tied grades--");
}
if(math==sci)
{
printf("\n--Math and Science tied grades--");
}
if(eng==sci)
{
printf("\n--Science and English tied grades--");
}
printf("\nYour average in 3 subjects:%f\n",avg);
break;
case 3:
printf("Enter beginning number: ");
scanf("%d",&b);
printf("Enter ending number: ");
scanf("%d",&c);
printf("\nCounting from %d to %d\n",b,c);
while(b<=c)
{
printf("%d ",b);
b++;
}
printf("\n");
break;
case 4:
printf("Enter Starting Series of Numbers: ");
scanf("%d",&a);
printf("Enter Ending Series of Numbers: ");
scanf("%d",&d);
diff=(d-a);
array[diff]=d;
printf("Select Array Value to Display: 0 to %d: ",diff);
scanf("%d",&e);
for(i=0;i<=diff;i++)
{
array[i]=a;
if(i==e)
{
printf("%d\n",array[i]);
}
a++;
}
break;
case 5:
printf("Abouts\n");
break;
case 6:
printf("Thank you!");
break;
}
}while(input != 6);
return 0;
}
`
This should be a comment, but I don´t have enough reputation yet.
As Gerhardh said, the problem is that you use diff before being initialized (which causes undefined behaviour)
As you said, if you move the initialization of array inside the case 4: after diff being set the program should work as intended. If you want to keep it before the switch, try using int* and malloc/free inside the case 4: (and add #include <stdlib.h>) Anyway, you should check diff as positive value before using it to set the size of array
About optimizing the code, you can skip the line array[diff]=d; because you are setting the same value inside the for loop. And you can remove the line a++; if you changes array[i]=a; -> array[i]=a+i;

How Terminate the Program on Pressing Enter key in C?

i am making a small project in which I have to convert different values to different bases like 10,8,16.But the problem is that I want to run the program till the user press 6 but if user hit Enter key then too it is waiting for the input rather than simply terminating. I'm using C11 version of C on online compiler.
and here's my code.
#include "ConvertInBackgnd"
#include<stdio.h>
int main() {
int choice;
printf("1 for Decimal to Binary\n2 for Binary to Decimal\n3 for Decimal to Octal\n4 for Octal to Decimal\n5 for Decimal to Hexadecimal \n6 for reconverting values \n");
l1: printf("Input your choice : ");
scanf("%d", &choice);
switch (choice) {
case 1:
dec_bin();
break;
case 2:
bin_dec();
break;
case 3:
dec_octal();
break;
case 4:
octal_dec();
break;
case 5:
dec_hex();
break;
case 6:
goto l1;
default:
printf("Invalid choice.");
break;
}
printf("Input 6 for reconverting the values.");
scanf("%d", &choice);
if (choice == 6) {
goto l1;
} else
return 0;
return 0;
}
I have made a separate file in which I have made functions and I thought it isnot necessary to put that code here too.
Consider using fgets to take input into a character array.
If needed, the input can be parsed with sscanf, strtol or others.
#include<stdio.h>
int main() {
char line[100] = "";
do {
printf("1 for Decimal to Binary\n2 for Binary to Decimal\n3 for Decimal to Octal\n4 for Octal to Decimal\n5 for Decimal to Hexadecimal \n6 for reconverting values \n");
printf("Input your choice : ");
fgets ( line, sizeof line, stdin);
switch ( line[0]) {
case '1':
printf ( "dec_bin()\n");
break;
case '2':
printf ( "bin_dec()\n");
break;
case '3':
printf ( "dec_octal()\n");
break;
case '4':
printf ( "octal_dec()\n");
break;
case '5':
printf ( "dec_hex()\n");
break;
case '6':
case '\n':
break;
default:
printf("Invalid choice.");
break;
}
if ( line[0] != '\n') {
printf("Input 6 for reconverting the values.");
fgets ( line, sizeof line, stdin);
}
} while ( line[0] == '6');
return 0;
}
To solve the enter problem:
scanf("%d", &choice)
Right now you are taking int value, try with char value and match the enter key with it. Then you'll be able to do what you are trying to do.
Ok, So I wanted to terminate the program if Enter key is pressed. So I was first a newbie then I realized that itsnot a big deal and to do so I just need to take a char as Input and then check that if that char input is enter key or not.
Its a sample code to terminate the program after pressing enter key.
char line;
scanf("%c",&line);
if(line=='\n')
return 0;
else
// your other code
But if your program doesnot take input then you should clear the buffer before the above provided code by adding just this single line before the above code.
while(getchar()!='\n');

do while loop in C

I am implementing a polynomial using array. This is the Problem Statement:
Write a menu-driven program to represent Polynomials as a data structure using arrays. and write functions to add, subtract and multiply two polynomials; multiply a polynomial with a constant, find whether a polynomial is a "zero- polynomial, return the degree of the polynomial. Assume that a new polynomial is created after each operation. How would you input and output polynomials?
I have created the input and output functions. But my do while loop is running twice.. Help me finding out why.
The do-while loop
do{
print_menu();
scanf("%c",&ch);
printf("\nch = %c\n",ch);
switch(ch){
case '1':
create_poly(poly,termpool,&next_poly);
break;
case '2':
print_poly(poly,termpool,&next_poly);
break;
case 'q':
break;
default:
printf("Invalid choice.");
}
}while(ch != 'q');
return 0;
}
The print_menu() function
void print_menu()
{
printf("\n1. Create a new polynomial.");
printf("\n2. Print polynomial.");
printf("\nq. Exit");
printf("\nEnter Choice:");
}
The create_poly() function
void create_poly(int poly[][2], int termpool[][2], int *next_poly)
{
int beg = poly[*next_poly][0];
int end, size, i, j;
printf("Enter size of the polynomial:");
scanf("%d",&size);
poly[*next_poly][1] = beg + size - 1;
end = poly[*next_poly][1];
printf("Enter terms of the polynomial(coeff then exponent):\n");
for(i=beg; i<=end; i++){
for(j=0; j<2; j++){
scanf("%d ",&termpool[i][j]);
}
}
poly[++(*next_poly)][0] = end + 1;
}
The print_poly() function
void print_poly(int poly[][2],int termpool[][2],int *next_poly)
{
int pos,beg,end;
int i;
printf("Enter position of the polynomial:");
scanf("%d",&pos);
if(pos-1 > *next_poly){
printf("Invalid position.");
return;
}
beg = poly[pos-1][0];
end = poly[pos-1][1];
for(i=beg; i<=end; i++){
printf(" %dx^%d +",termpool[i][0],termpool[i][1]);
}
printf("\b = 0");
}
Here is a sample output:
1. Create a new polynomial.
2. Print polynomial.
q. Exit
Enter Choice:1
ch = 1
Enter size of the polynomial:2
Enter terms of the polynomial(coeff then exponent):
2 4
6 7
1. Create a new polynomial.
2. Print polynomial.
q. Exit
Enter Choice:
ch =
Invalid choice.
1. Create a new polynomial.
2. Print polynomial.
q. Exit
Enter Choice:q
ch = q
Tried flushing the stdin… The problem stays. Printing the value of ch in each step, I think it is a whitespace. Where does the white space comes?
The answer to abnormal behavior of scanf answers this question also.
If you test the next code you will note the same problem
int main() {
char c;
do {
scanf_s("%c", &c);
if (c != 'q')
printf("test scanf() function\n");
} while (c);
}
the scanf() function works when the enter key is pressed, but this insert another char in the buffer input, the char of new line '\n', it is taken again by scanf() because the loop block. Try to change the previous code by this code:`
do {
scanf_s("%c", &c); // or c = getchar();
switch (c){
case '\n':
break;
default:
printf("test scanf() function\n");
}
} while (c);`
and will work fine. In your code only add a new case in the switch block:
switch(ch) {
case '1':
create_poly(poly,termpool,&next_poly);
break;
case '2':
print_poly(poly,termpool,&next_poly);
break;
case '\n':
break;
case 'q':
break;
default:
printf("Invalid choice.");
}
sorry, English is not my native language
There's an extra character waiting to be consumed after you make your initial choice, that's why the loop is executing twice.
See this question on the comp.lang.c FAQ

Last array number keeps going wrong after switch statment

For example if i enter: "123456-7". The output at the first print statement would be: "123456-7" and at the 2nd print statement it would be "7". Which is correct.
But at any point after the break if I print the array again the print statement would go wrong in the last digit. It would look like: "123456-1" and the second would look like "1".
#include <stdio.h>
int main()
{
int lotoNumbers[6];
int ticketNumbers[6];
char option;
while(option != 'C')
{
printf("Your option:");
scanf(" %c", &option);
switch(option)
{
case 'W': printf("Please enter todays winning ticket number:");
scanf("%1d%1d%1d%1d%1d%1d-%1d", &lotoNumbers[0], &lotoNumbers[1], &lotoNumbers[2], &lotoNumbers[3], &lotoNumbers[4], &lotoNumbers[5], &lotoNumbers[6]);
printf("Your loto ticket number is: %d%d%d%d%d%d-%d\n", lotoNumbers[0], lotoNumbers[1], lotoNumbers[2], lotoNumbers[3], lotoNumbers[4], lotoNumbers[5], lotoNumbers[6]);
printf("----The following numbers matched! %d\n", lotoNumbers[6]);
break;
case 'T': printf("Please enter your ticket number:");
scanf("%1d%1d%1d%1d%1d%1d-%1d", &ticketNumbers[0],&ticketNumbers[1],&ticketNumbers[2],&ticketNumbers[3],&ticketNumbers[4],&ticketNumbers[5],&ticketNumbers[6]);
printf("Your loto ticket number is: %d%d%d%d%d%d-%d\n", ticketNumbers[0], ticketNumbers[1], ticketNumbers[2], ticketNumbers[3], ticketNumbers[4], ticketNumbers[5], ticketNumbers[6]);
break;
case 'C': printf("Computing....\n");
break;
case 'Q': printf("The program will now quit. Thank you for playing LOTO 649.\n");
return (0);
break;
default: printf("You entered an invalid option. The program will now terminate.\n");
return (0);
}
}
printf("The numbers are:%d%d%d%d%d%d-%d\n", lotoNumbers[0], lotoNumbers[1], lotoNumbers[2], lotoNumbers[3], lotoNumbers[4], lotoNumbers[5], lotoNumbers[6]);
printf("The number is: %d\n", lotoNumbers[6]);
return 0;
}
You didn't allocate enough space for your arrays. The number used to allocate space for an array is the number of entries in the array, not the last index number. Index 6 is the 7th item and is past the end of the array. The value of lotoNumbers[6] is undefined and can change randomly, because the program is using that memory for something else.
int lotoNumbers[6];
int ticketNumbers[6];
That 6 should be 7.

Switch case missing in C program

#include<stdio.h>
#include<conio.h>
void inversion(void);
void ways(void);
void prime(void);
void power(void);
void fibonacci(void);
void main(void)
{
char choice;
printf("Enter a choice:\n 1.Perform inversion of digits \n 2.calculate all the ways that a positive number can be get by adding \n 3.Calculate prime numbers in a range\n 4.Calculate power of a number. \n 5.generate a particular numebr of fibonacci");
choice==getche();
switch(choice)
{
case 1: inversion();
break;
case 2: ways();
break;
case 3: prime();
break;
case 4:power();
break;
case 5:fibonacci();
break;
}//switch ends
//printf("Do you want to perform this once more? (Y?N):");
//}
//while (choice=='y'||choice=='Y');
getch();
}
void inversion(void)
{
clrscr();
int num,i,x,y;
printf("Enter a 4 digit number:");
scanf("%d",&num);
for(i=1;i<=4;i++)
{
x=num%10;
y=num/10;
printf("%d",x);
num=y;
}// for ends
getch();
}
void ways(void)
{ clrscr();
int num,i,j;
printf("Enter the number:");
scanf("%d",&num);
for(i=1;i<=num;i++)
for(j=1;j<=num;j++)
if(i+j==num)
printf("%d+%d=%d",i,j,num);
getch();
}
void prime(void)
{
int num1,num2,i;
printf("Enter a range separated by space:");
scanf("%d %d",num1,num2);
for(i=2;i<num2;i++)
{ if(num1%i!=0)//is prime
printf("%d",num1);
}//for ends
getch();
}//prime ends
void power(void)
{
int num,index,i,result=1;
printf("Enter the number and its index (eg.2^3)");
scanf("%d %d",&num,index);
for(i=1;i<=index;i++)
result=num*result;
printf("%d",result);
}//power function ends
void fibonacci(void)
{
int num,x=1,y=1,i,z;
printf("Enter the term you want to find in fibonacci series:");
scanf("%d",&num);
if (num==1)
printf("it is the 1st & 2nd term");
for(i=1;i<=num+2;i++)
{
z=x+y;
if (i==num)
printf("%d",z);
x=y;
y=z;
}
printf("%d");
}//fibonacci func ends
There are a lot of problems in your code:
# I would like to suggest you to use getchar() instead of getche() for a character input.
# Now you are using a charcter for numeric options which you could have avoided by defining your choice variable as integer:
int choice;
scanf (%d, &choice);
# also if you were using char choice;
you are having cases as:
case 1: inversion();
break;
while your choice variable was char
so you should have case like:
case '1': inversion();
anyways if you will define choice as int then your code should work fine.
or you can change your cases also with case values in single quotes.

Resources