Johann Strauss
Johann Strauss

Reputation: 23

Convert a char type stored in an array to an int variable

I'm currently working on a project and I need to do something very specific. I need to store a value in a database of sorts using a char array, but I also need to store the value of a multiplication in the last slot of it and I have no idea how to do this. Casting the char variable and multiplying it seems to store garbage on the int as I get values way off the range it should be. Another suggestion I tried was using memset() to manually set the value but I don't quite know how to go about that.

Here's my code

int form_fill(int room_ID, char database[rooms * floors * req_data][20]) {
    printf ("Enter the first name\n");
    fflush(stdin);
    gets (database[room_ID]);
    printf ("Enter the second name\n");
    gets (database[room_ID + 1]);
    printf ("Enter the third name\n");
    gets (database[room_ID + 2]);
    printf ("How many days will the guest stay?\n");
}

Ideally the days the user inputs will be stored in database[room_ID + 3] as a char and multiplied by another variable declared earlier as global and the result stored, as a char, in database[room_ID + 4]. Anyone got any solutions for this?

ps. I know using gets is unsafe, but that's what the teacher asked so I have to.

Upvotes: 2

Views: 112

Answers (1)

Sourav Ghosh
Sourav Ghosh

Reputation: 134336

Your problem statement is not very clear, but as of now, a generic way to achieve what you want is to

  1. Take the input from user for "How many days will the guest stay?" using fgets().
  2. Convert the string input to int by using strtol() and store in a temporary int variable.
  3. Multiply that value with your global char.
  4. Print the result to database[room_ID+4] using snprintf().

Upvotes: 2

Related Questions