将单个字符传递到C 中的函数
passing a single character to a function in C++
我已经通过网搜索了我的问题,我知道,要将数组值从函数返回到我们的主函数(或任何其他功能),我需要使用指针(它可以用各种方法来完成),我也可以使用它们来解决我的问题请尽可能多地解释,这是我的小程序:
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
相关文章:
- C++调用具有 *this 属性的单个帮助程序函数
- C++:带有大括号初始化列表的函数调用表达式 - 标准是否规定在单个元素列表的微不足道的情况下忽略大括号?
- 如何在 c++ 中将整个数组初始化为类构造函数中的单个元素
- 是否可以使用单个定义定义函数的常量和常规版本?(使用模板,自动,decltype等)
- 使用可变参数函数将整数和/或整数数组放入单个 int 数组中
- 多个可变参数函数的单个模板参数包?
- 将指向多维数组向量中的单个项的指针传递给函数 c++
- 如何将多个函数重载作为单个参数传递?
- 具有默认值的单个参数构造函数是否与默认构造函数相同?
- 如何使用 TBB 在单个线程中运行函数
- 模板化虚拟函数,管理单个类的不同类属性
- 如何对具有相同类型的成员使用单个函数 C++.
- 如何使用每个对象的单个构造函数参数动态分配C++对象数组?
- 外部 C 和 C++ 对于单个函数(bsearch / qsort)的目的是什么?
- 如何使用 std::cout 或 std::ofstream 作为单个函数的输入?
- C 使用单个函数对具有多种值类型的数组排序
- 如何使用单个对象调用具有相同名称的两个类函数
- 如何在C 中的单个构造函数中调用多个构造函数
- C++ 中深度嵌套函数的单个捕获全部语句?
- C :类 - 超载构造函数 - 单个变量