C programming If statement variable change [closed] - c

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
Later on in my program I want to print out the destination that the user has chosen here, how do I do this?
void create(){
char name[200],from,to;
int age;
printf("Please enter your name :\n");
scanf("%s",&name);
printf("Please enter your age :\n");
scanf("%d",&age);
printf("Pick your current destination");
printf("\n1 for London\n2 for Manchester\n3 for Brighton\n4 for
Liverpool\n4 for reading\n5 for coventry\n");
scanf("%s",&from);
if(from == 1){
printf("Select your desired destination %s",&from);
from =("London");

It seems you mean
scanf( " %c", &from );
^^^^^
//...
if( from == '1' ){
^^^

In short, if you want to access the local variable from, declared inside the functoion create(), it is not possible [you can hope the variable lies in the same address after the function has returned and try to access that same address in hope that the value is still there but this is UB].
Waht you can do is to declare it globaly, or return it from the function
// option 1) global variable
char from;
int main(){
... create(); // don't declare from inside the function, because it is already declared globaly
// do something with from
... }
// option 2) return from function - need to change the create function to return the from variable
char from;
int main(){
from = create();
// do something with from
... }
Note that you're using scanf / printf incorrectly:
scanf("%s",&from); should be scanf("%c",&from); since from is char, not char[] or char*
printf("Select your desired destination %s",&from); should be printf("Select your desired destination %c",from);

Here...The program doesn't have any variable for the location.... It means you can't fetch data to print from no where.... So the program must have the data in program in itself.... if not..... No source no data....
If you want to continue the program as it is... You can use switch statement and display the value later as:
switch(from){
case 1:
printf("London\n");
break;
case 2:
printf("Manchestar\n");
break;
case 3:
printf("Brigeton\n");
break;
default:
//(default Option);
}
You can also use character array.
for eg:
int from;
int location[3][10]={"London","Manchestar","Brigeton"};
printf("\n1.London\n2.Manchestar\n3.Brigeton");
printf("\nChoose whose city do you want to visit: ");
scanf("%d",&from);
printf("You have choosen %s",location[from-1]);
In this way, we can give choice to end user and also we can fetch data directly...

Related

Switch with goto statement in function keeps running ad infinitum? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
This is the relevant code, I'm trying to write a function to pick type of account and when I run this, it keeps running in a weird loop. Any solutions?
void AccType(){
wrongInput:;
int typCho;
printf("What type of account do you want to open?\nPress 1 for Current\n2 for savings\n3 for retirement:\n");
scanf("%d",typCho);
switch (typCho) {
case 1:
strcpy(PracRec.AccTyp,"Current");
break;
case 2:
strcpy(PracRec.AccTyp,"Savings");
break;
case 3:
strcpy(PracRec.AccTyp,"Retirement");
break;
default:
printf("Please enter a valid choice!!\n");
goto wrongInput;
}
}
The second argument of scanf needs to be a pointer (memory adress) to an integer...
So, replace the line:
scanf("%d",typCho);
with:
scanf("%d", &typCho);
& is an operator that returns the memory address of the operand at right.
This is needed because scanf is going to change the value inside the memory address which relates to the variable.
When you put only typCho as the argument, it probably made the program to write the input at a random memory location, as the variable was also uninitialized.
Also, consider avoiding the use of goto, as pointed in the previous comments.
You could easily do the same thing with a construct like:
do { ...code... } while (condition);

"Database" in c (not actual database, just a simple thing) [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
The main idea of the code below is to let me add, delete etc portions of the arrays so that it looks more or less like a store's database (did this because I have no idea how to use pointers and etc). I got the thing almost figured it out, but i am having 2 big problems:
The first problem is that I get a "segmentation fault (core dumped)" when I run the code and select case 1. I don't even know what the error means so I don't see how can I fix it.
The second problem which is probably my biggest, can anybody tell me how can I store the arrays in a file in such a way that when I run the program again, the arrays won't be empty, but will take their elements from a file, and save in the same file when I exit (that's why I used the word database).
include stdio.h
include stdbool.h
int main()
{ bool bExit = false;
int select, i, price[5], amount[5];
char *name[5];
do
{ printf("What would you like to do ?:\n");
printf("1) Add products \n");
printf("2) Delete products \n");
printf("3) Find product by name (shows position and price) \n");
printf("4) Find product by position (shows name and price) \n");
printf("6) Display all info of all products \n");
printf("7) Modify amount of existing product \n");
printf("8) Modify price of existing product \n");
printf("9 Exit \n");
scanf("%d", &select);
switch (select)
{
case 1:
{
for(i=1;i<=5;i++)
{
printf("Name: ");
scanf("%c\n", *name[i]);
printf("Price: ");
scanf("%d\n", price[i]);
printf("Amount: ");
scanf("%d\n", amount[i]);
}
break;
}
case 2:
... bla bla bla ...
default:
{
printf("Good Bye \n");
bExit = true;
break;
}
You do not need to use any pointer for char *name[5]. Use char name[5] instead. Probably the segmentation fault comes from this statement
scanf("%c\n", *name[i]);
for the second question create a file and open it whenever you want to read/write. Something like
File *fptr=fopen("database","w");
for(i=0;i<5;i++){
fprintf(fptr,"%s\n",name[i]);
}
take a look in the link here:http://www.programiz.com/c-programming/c-file-input-output
You don't allocate any memory for your names
char* name[5] is just an array of 5 pointers to chars.
you could do char name[5][100] its fixed to 100 chars.
Going forward, you really need to alocate memory for strings, and also allocate memory for "database" entries.
You need to save your "database" to disk, and then load it again when it starts
Create a big array (maybe a vector<>) where you save all prices and names etc. Then when you use scanf for price and amount use & (like scanf("%d", &price[i]) ).
Then you write the values on a .txt file (you can use c++ ofstream, google for that) and when you execute your code, first of all you read previous values from your file (using ifstream).

(C) Trouble with adding integers [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
I'm having troubles with a simple addition calculator.
After I put in the first number, the program crashes.
#include <stdio.h>
int main()
{
printf("Addition calculator\n");
int num1,num2;
printf("Enter the first number: ");
scanf(" %d",num1);
printf("\nEnter the second number: ");
scanf(" %d",num2);
int sol;
sol=num1+num2;
printf("The solution is %d", sol);
return(0);
}
scanf(" %d", &num1);
scanf expects an address of a variable, so it can change its value. You're passing in the value of num1 as an address, which has a very very very high probability to be somewhere your program is not allowed to write.
Same for num2.
I love analogies, so...
Think about this code:
int recordASeven(int x) {
x = 7;
}
int main() {
int y = 0;
recordASeven(y);
printf("y is %d\n", y);
}
This prints 0. Why? It's like this: You have a piece of paper in your locker, with "0" written on it. You copy the "0" carefully onto another piece of paper, give it to a friend and say "write down 7 here instead". He does so, then throws paper away. You look into your locker, and there's your own paper with "0" on it. Because you're passing your friend a copy of your paper and not your own paper, he can't change your own original. Same with functions in C - they can't ever change the variables they get passed in. So scanf can't ever modify the variables directly.
int recordASevenBetter(int *x) {
*x = 7;
}
int main() {
int y = 0;
recordASeven(&y);
printf("y is %d\n", y);
}
Now here you take a blank piece of paper, give him the combination that will open your locker, and give that to your friend, saying "go to my locker, write down 7 on the paper in there". When you go and inspect the paper in your locker later, sure enough, there's "7" on it. In C speak, "&y" will give you the location of where the value of y is ("pointer"), so that anything can change it; "*x" will access the value in the location specified by the value of x.
int recordASevenAndFailMiserably(int *x) {
*x = 7;
}
int main() {
int y = 0;
recordASeven(y);
printf("y is %d\n", y);
}
Finally, here's your problem: you give your friend a copy of your "0", and tell him it's your locker combination. When he goes to open your locker, he gets frustrated, trashes your room and pees on the floor.
In this case, the compiler can detect the disparity, since there is a clear mismatch between the declared and the provided types, and the compiler will refuse to do it. But scanf uses variadic argument list, which means the declaration does not list the parameter types. It will be the responsibility of scanf to decypher the format and interpret the bag of bytes it gets as something sensible. And the compiler can only stand by and watch shaking its head (when you enable warnings) as you lie to scanf about what you're giving it.
Please change it to &num1 and &num2 as mentioned by Amandan. You have to pass the address of the variable.

fwrite there got bug, but i don't know how? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Closed 9 years ago.
Improve this question
help me solve this coding... it keeps said got errors :-
it said fwrite there got problems..
// #define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
struct prod
{
char ProductCode [5];
int Expired_year;
char Product_country [25];
}product;
struct prod product;
void main()
{
char x ;
FILE* data;
data = fopen("product.dat","wb");
while(x != 'N')
{
printf("Enter product code :");
scanf("%s", product.ProductCode);
printf("Enter expired year of the product :");
scanf("%d", &product.Expired_year);
fflush(stdin);
printf("Enter product country :");
scanf("%[^\n]", product.Product_country);
fflush(stdin);
fwrite(&prod, sizeof(product), 1, data);
printf("\nPlease enter anykey to continue or 'N' to stop: ");
scanf("%c", &x);
fflush(stdin);
printf("\n");
}
fclose(data);
}
fwrite(&prod, sizeof(product), 1, data);
prod doesn't refer to a struct instance but to the name of the structure, it should be
fwrite(&product, sizeof(product), 1, data);
Wrong syntax for fwrite().
It should be,
fwrite(&product, 1, sizeof(product), data);
The first argument needs a pointer to some data, but &prod is not valid. prod is a type, not an instance variable. You probably want to change it to fwrite (&product, ...)
First of all, you're declaring struct prod product twice.
Second, the correct sintax for fwrite() is fwrite(&product,sizeof(struct prod),1,data);

Pointers dereferencing, bad pointers [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 8 years ago.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Improve this question
I am trying to program an encrptor and decryptor. My problem is a pointer that I assigned value first still has the same value as the second. I tried to use free but the problem is still the same.
For example, I typed aslkdjlasc(sample only)
and the output would be:
helloworld
I try to run the program again, then I type daskjda
the output would be like
doctorxRLD
RLD is from the past value of this pointer. It's supposed to be 7 characters only, but since helloworld is 10, the first 7 letters are replaced by the encryption but the last 3 characters are still printed.
What do I do?
UPDATE: HERE IS PART OF THE CODE:
void encrypt(char *crypt)
{
char *plaintext,*encryption,slash=0x2F;
int i,j,k,flags,f;
encryption=(char *)malloc(sizeof(int));
plaintext=(char *)malloc(sizeof(int));
printf("Enter plaintext, spaces,commas,and dots should be represented as /:\n");
scanf("%s",&*plaintext);
for(i=0;i<strlen(plaintext);i++)
{
j=1;flags=0;
while(j<53 && flags==0)
{
if(plaintext[i]==slash)
{
encryption[i]=slash;
flags=1;
}
if(plaintext[i]==crypt[j])
{
encryption[i]=crypt[j-1];
flags=1;
}
k=j+2;
j=k;
}
}
printf("%s",encryption);
free(encryption);
free(plaintext);
getch();
}
HERE IS THE MAIN
main()
{
char c;
int timer;
char crypt[53]="***i have hidden my encryption code***";
clrscr();
printf("Press e to encrypt, d to decrypt, ESC to exit.\n");
c=getch();
switch(c)
{
case(0x1b):
exit(0);
break;
case(0x64):
decrypt(crypt);
break;
case(0x65):
encrypt(crypt);
break;
default:
printf("INVALID. FORCE EXIT IN 3 SEC0NDS.");
delay(3000);
exit(0);
}
getch();
}
In your code you are allocating integer size (4 bytes ) of memory for a string
When you do
plaintext=(char *)malloc(sizeof(int));
Then by doing this
scanf("%s",&*plaintext);
your are possibly scanning a string of size more than that four characters ( however you allocated only four bytes) also
scanf("%s",&*plaintext); is equivalent to scanf("%s",plaintext); ( with the previous statement you are adding unnecessary computations.
it's me. I got it already. Thanks to all your comments though some are harsh. haha
I refrained from using malloc because apparently DCoder points out I do not know how to use them.
Thanks Sanyam Goel I have fixed my scanf too.
I used only 2 pointers instead of 4. What I did was I instantiated them in the main function instead of in each of the decrpyt and encrypt functions. Like this:
main()
{
char c,*from, *to; ..........
void encrypt(char *crypt,char *plaintext,char *encryption)
void encrypt(char *crypt,char *ciphertext,char *decryption)
So when I call either of them, I just put:
case(0x64):
decrypt(crypt,from,to);
break;
case(0x65):
encrypt(crypt,from,to);
break;
And at the end of the switch in the main function:
free(from); from=NULL;
free(to); to=NULL;
So now I have eliminated unnecessary pointers and extra processes.
THANK YOU EVERYONE. :)

Resources