输出字符的ASCII值

时间:2018-03-26 15:01:09

标签: c++ ascii

#include <iostream>

using namespace std;

int main()
{
    char x;
    cout << "enter a character:";
    cin >> x;
    cout << "ASCII Value of " << x << "is" << string(x);
    return 0 ;
}

错误是

main.cpp||In function 'int main()':| 
main.cpp|10|error: invalid conversion from 'char' to 'const char*'| 
main.cpp|10|error:   initializing argument 1 of 'std::basic_string<_CharT, _Traits,_Alloc>::basic_string(const _CharT*, const _Alloc&) [with _CharT = char, _Traits = std::char_traits<char>, _Alloc = std::allocator<char>]'|
||=== Build finished: 2 errors, 0 warnings ===|

4 个答案:

答案 0 :(得分:3)

std::cout << "ASCII Value of " << x << "is" << (int)x;

是一种方式(强制转换绕过I / O流库对char类型的特殊处理),但是这将输出你的平台的字符编码值,这不是必然< / em> ASCII。

便携式解决方案要复杂得多:您需要在能够存储7位无符号值的128个元素元素数组中对ASCII集进行编码,并将x映射到该元素的合适元素。

答案 1 :(得分:0)

有3种方法可以解决这个问题:

  • 使用to_string
  • 将正确的值传递给cout
  • 正确使用std::string课程

标记解决方案(评论中的数字)。

使用std::to_string

从C ++ 11开始,有将数字转换为字符串(to_string)的功能:

/*(1)*/        std::cout << std::to_string( x );

char参数没有专门化。所以价值被隐含地转换。

将正确的值传递给cout

cout会将char个对象的值显示为字符。 如果我们想输出char对象的值,我们需要将它转换为cout输出的类型而不是字符。

C ++标准保证:

1 == sizeof(char) <= sizeof(short) <= sizeof(int) <= sizeof(long) <= sizeof(long long)

因此可以使用任何这些整数类型。通常选择int

此处可以使用4次转换:

1)Implicit - “只要某个类型T1的表达式在不接受该类型的上下文中使用,但接受其他类型的T2,就会执行隐式转换;”

/*(2)*/        int i = x;
               std::cout << i;

2)Explicit - “使用显式和隐式转换的组合在类型之间进行转换。”

/*(3)*/        std::cout << (int)x;

/*(4)*/        std::cout << int(x); // unsigned int(x) - is invalid, 
                                    // has to be a single-word type name

3)一名命名演员。

/*(5)*/        std::cout << static_cast<int>(x);

4)使用T{e}表示法构建

/*(6)*/        std::cout << int{x};
  

T{e}构造语法明确表示需要构造。 T{e}构造语法不允许缩小范围。 T{e}是从表达式e构造类型T的值的唯一安全和通用表达式。强制转换符号T(e)(T)e既不安全也不通用。

关于转化, C ++核心指南指定了以下(以及其他)

在这种情况下,我建议(3)或(4)。

正确使用std::string

stringbasic_string

的特化
using string = basic_string<char>;

basic_string有很多constructors

只有2个构造函数,可以使用预定义数量的字符;

  

basic_string( size_type count, CharT ch, const Allocator& alloc = Allocator() );

     

构造具有字符ch的计数副本的字符串。如果count> gt = = npos。

,则行为未定义
/*(7)*/        std::string s = std::string( 1, x );
  

basic_string( const CharT* s, size_type count, const Allocator& alloc = Allocator() );

     

使用s指向的字符串的第一个计数字符构造字符串。 s可以包含空字符。字符串的长度是count。如果s没有指向CharT的至少count个元素的数组,则行为是未定义的,包括s是空指针的情况。

/*(8)*/        std::string s = std::string( &x, 1 );

答案 2 :(得分:-2)

let item = {id: this.id, name: this.name, price: this.price, amount: this.amount}
let hasItem = false;

this.cart.items.forEach(element => {
    if (element.id === item.id) {
        element.amount += item.amount
        hasItem = true; 
    }
})
if (!hasItem) {
    this.cart.items.push(item);
}
  

你的意思是返回试试这段代码

答案 3 :(得分:-3)

#include <iostream>

using namespace std;

int main()
{
    char x;
    cout<< "enter a character:";
    cin>>x;
    cout<< "ASCII Value of "<< x<< "is"<< char(x);
return 0 ;
}
  

试试这个名为return