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

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).

Related

C programming If statement variable change [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 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...

How to read integers separated by a comma and a white space into an array in C [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 7 years ago.
Improve this question
I need a function that gets input in the form of int1, int2, ..., intn.
I neeed to store the values of these integers in an array. A separate function is used to get the number of integers to be read. How can I make the two functions work?
If it's not clear, it's something like this:
function1 gets an integer to get the number of input to be read. Then the function2 will read that input plus one but the input must be in a single line and must be separated by a comma and/or a white space.
Function1 gets, for example 5. function2 will want to read input like: 3, 21, 5, 1, 5, 2 and store it into a separate array for later use.
Can anyone help? Thanks. I thought of using loops but I remembered that the input must be in one line. Maybe scanf? With [^,]? But how do I make it work with the first function?
Try this:
#include <stdio.h>
void getInput(int sizeOfInput, int arr[]) {
int i = 0;
printf("IN");
for(; i < sizeOfInput - 1; ++i) {
scanf("%d, ", &arr[i]);
}
scanf("%d", &arr[i]);
printf("OUT");
}
main(){
int sizeOfInput = 0;
printf("Enter how many numbers do you want to enter?");
scanf("%d", &sizeOfInput);
int arr[sizeOfInput];
getInput(sizeOfInput, arr);
}
Sorry I am lazy but for you to learn it would be the best to figure out what this code does before you use it, that is also a reason why I did not comment it.

(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.

print the changed variable before the calculation is done [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
in a c program, i want the variable 'count' to be printed at the beginning of the program. But the calculation for the value of 'count' is done later. How do you accomplish this?
count = 0;
printf("the value of count is : %d", count);
count = 20;
I know in this case, the output is 0. But I need 20 to be printed.
The idea of program flow is that commands are executed in a certain order. You don't expect the waiter to bring you your meal before you have told him what you want to eat - but that seems to be what you are asking.
Of course the order of lines in a file is not necessarily the order of execution: you have have a line "at the start of the file" that is executed later: for example
#include <stdio.h>
// we define the print statement here:
void printCount(count) {
printf("the count is now %d\n", count);
}
int main(void) {
int count = 20;
printCount(count); // but we don't execute it until we get here...
return 0;
}
Now your "print" statement occurs (in the file) before you assign (calculate) count - but of course they are being executed in the correct order.
afterthought
If it's a case of printing "the number of cases is n", you could of course do
printf("the number of cases is ");
cases = 5; // whatever math is needed happens here...
printf("%d\n", cases);
and the result is
the number of cases is 5
just as you wanted... this works because there was no carriage return after printing "the number of cases is" - so the number follows when you have figured it out.
edit
Reading through the question and comments one more time I think I understand what your issue is. You have a loop that counts a number of inputs (say the number of lines in a file) and want to print both the total number of cases (not known before the loop) and something about each case (discovered during the loop) but without having to loop over all the data twice. There is a way to do this, using a print buffer. If data access is really slow and looping twice would be prohibitive, this might be an option. You would want to initialize a "sufficiently large" print buffer in memory and use snprintfto create the string you need. In reality you will "loop over" the bytes in the output string twice but there is minimal performance penalty (compared to everything else). Incomplete example:
int count=0,num, sofar=0;
char buf[2000];
// assume file is opened and handle is fp
while(true){
if (fscanf(fp, "%d", &num) <1) break;
sofar+=snprintf(buf+sofar, "%d\n", 2*num); // some "math" on number for each "case"...
count++;
}
printf("There were %d lines\n", count);
printf("Here they are multiplied by two:\n");
printf("%s\n", buf);
Obviously the above is incomplete - you need to check for errors, open/close the file, etc - I am just trying to point out the principle - this way you only loop through the data (file) once but print the count before the contents.
you can't print 20. how can you print a variable before its get initialized?

Error : Find Largest Number in given numbers [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
This C program helps to find the largest number in given numbers but it is not working. I have highlighted the line where the problem is.
#include<stdio.h>
int main(){
int n,num,i;
int big;
printf("Enter the values of n: ");
scanf("%d",&n);
printf("Enter %d Numbers :",n);
scanf("%d",&big);
for(i=2;i<=n;i++){
scanf("%d",&num); //here is the problem..
//what it is reading as `num` without asking me to entering any thing ?
if(big<num)
big=num;
}
printf("Largest number is: %d",big);
return 0;
}
If you need the program to ask for input in a user-readable way, you can put
printf("Enter number #%d:",i+1);
before that line with scanf.
Anyway, the program will do its job just the same if you remove all printf's (and so, print no prompts, only wait for user input). They are only for users' convenience.
Your first scanf command only reads in your first number from stdin. The one on line 14 reads the rest, one per time around the loop. Then each one gets compared to variable "big", and replaces it it necessary.

Resources