Convert char to int in C and C++

前端 未结 12 1996
梦毁少年i
梦毁少年i 2020-11-22 02:41

How do I convert a char to an int in C and C++?

12条回答
  •  被撕碎了的回忆
    2020-11-22 03:12

    It sort of depends on what you mean by "convert".

    If you have a series of characters that represents an integer, like "123456", then there are two typical ways to do that in C: Use a special-purpose conversion like atoi() or strtol(), or the general-purpose sscanf(). C++ (which is really a different language masquerading as an upgrade) adds a third, stringstreams.

    If you mean you want the exact bit pattern in one of your int variables to be treated as a char, that's easier. In C the different integer types are really more of a state of mind than actual separate "types". Just start using it where chars are asked for, and you should be OK. You might need an explicit conversion to make the compiler quit whining on occasion, but all that should do is drop any extra bits past 256.

提交回复
热议问题