将单个字符传递到C 中的函数

passing a single character to a function in C++

本文关键字:函数 单个 字符      更新时间:2023-10-16

我已经通过网搜索了我的问题,我知道,要将数组值从函数返回到我们的主函数(或任何其他功能),我需要使用指针(它可以用各种方法来完成),我也可以使用它们来解决我的问题请尽可能多地解释,这是我的小程序:

char Calc(char);
int main(){
    Calc('1');
    return 0;
}
char Calc(char a) {
    a = int(a);
    std::cout << a <<std::endl;
    std::cout << int('1');
    _getch();
    return 'c';
}

根据ASCII表," 1"的整数为49,因此我的 func 函数中的两个命令都必须显示相同的内容,即49,但它显示为输出:

1
49

我在这里想念什么?谢谢。

std::cout << a <<std::endl;

显示1,因为std::basic_ostream& operator<<作为非成员操作员对char S重载,并显示其相应的ASCII值。另一方面,

std::cout << int('1') <<std::endl;

char '1'显示为int(由于显式铸件),因此您会看到49的相应ASCII索引。这是因为对于算术类型,成员std::basic_ostream& operator<<被拾取。

请注意,您的行

a = int(a);

什么都不做,它不会将a的类型更改为int;它只是将RHS投入到int,然后将int分配给原始char(显然没有数据丢失)。在C或C 中,该类型在编译时以石材为石头。

进行a = int(a);时,您将char升级为int。但是将此结果分配给一个。因此,您将int投射到char,这可能会丢失数据。

但实际上您只是说'1' = int('1'),所以您什么也没做。尝试a = int(42000)

a是char,因此将int分配给A将分配字符 1的ASCII代码的字符值:

char a = (int)a;// a = '1' (int)a = (int)'1' = 49 so the result is: 
a = (char)49 = 1; // because assigning an integer to char will implicitly convert it.
cout << (int)'1'; or int i = (int)'1';
the ASCII value of character '1' is as we said below is 49
cout << i; // 49