0

So I was wondering how can I convert my string char code[5] to an integer number, so I can make a multiplication.

For example on my code I want to do this:

int duracaoinicial = code[2] * 100;

and

int duracaofinal = code[4] * 100;

But my string is CHAR so I can't do that.

Hope you guys can help me, I feel like that it is pretty simple but I'm stuck I don't know why.

gre_gor
  • 6,669
  • 9
  • 47
  • 52
  • 5
    Possible duplicate of [How to convert a string to integer in C?](https://stackoverflow.com/questions/7021725/how-to-convert-a-string-to-integer-in-c) – MFisherKDX May 06 '18 at 22:34

1 Answers1

2

You can do it like so:

int duracaoinicial = (code[2] - '0') * 100;

This will convert the single character into a digit and multiply by 100. Example here.

Rivasa
  • 6,510
  • 3
  • 35
  • 64
  • Doesn't seems to work, heres all my code if it helps: [link](https://onlinegdb.com/HJuUoGC6G) – Fernando Caria May 07 '18 at 18:32
  • @FernandoCaria You have not put anything into: `codigo` array, so it is undefined behavior. There needs to be actual digits in there. – Rivasa May 07 '18 at 19:30
  • So my problem is that the user will need to insert a code with 5 digits and each digit will do something. The first digit will light up the number of the LED, the second is the current state, the third will define the time that the LED will be lighted up, etc.. I can't do that? Or I need some other function? – Fernando Caria May 08 '18 at 07:58
  • You need to multiply (use my line) AFTER you have gotten the code from the user. Using it before does not work, since it is random data. – Rivasa May 08 '18 at 13:17