【问题标题】:Char-to-int conversion in C++C++ 中的字符到整数转换
【发布时间】:2015-07-08 00:04:45
【问题描述】:

在 Stroustrup 的编程中的第 3.9.1 章“安全转换”中,他有代码来说明从 int 到 char 并返回的安全转换。

#include<iostream>
#include<string>
#include<vector>
#include<algorithm>
#include<cmath>
using namespace std;

int main()
{

    char c='x';
    int i1=c;
    int i2='x';

    char c2 = i1;

    cout << c <<'<< i1 << ' << c2 << '\n';

    return 0;
}

它应该在屏幕上打印x 120 x。

但是,我无法让它工作,我不知道为什么。我得到的结果是x1764834364x。

我还收到 3 个警告(在 Xcode 6.3.1 中)。

  • 多字符字符常量。
  • 字符常量对于它的类型来说太长了。
  • 未使用的变量 i2。

是什么原因造成的?

【问题讨论】:

  • 您确定您复制的代码正确吗?正如消息所说,在'&lt;&lt; i1 &lt;&lt; ' 周围使用单引号是一个多字符字符常量,这几乎不是您想要的。也许您希望cout &lt;&lt; c &lt;&lt; ' ' &lt;&lt; i1 &lt;&lt; ' ' &lt;&lt; c2 &lt;&lt; '\n'; 在您要打印的内容之间添加空格。
  • 我完全按照书中的内容复制了它,但你是对的 Greg。如果我按照你的建议去做,我会得到想要的答案。我很失望书中的示例没有更精确,但我感谢您的帮助。
  • 嗯,你说得很对。我看了page 79 in Google Books,果然,书中的代码肯定是不正确的。

标签: c++


【解决方案1】:

问题出在这里:

'<< i1 << '

编译器会给你一个警告(至少是 gcc):

警告:字符常量对于它的类型来说太长了

它认为您正在尝试显示单个char(撇号之间的内容),但实际上您正在传递多个chars。您可能只想添加空格,例如

' ' << i1 << ' '

【讨论】:

    【解决方案2】:

    我想补充一些可能对有类似情况的人有用的相关信息:

    当您使用单引号打印比字符更长的内容时,您会得到如此奇怪的输出。例如:

    cout << 'a'<<'    '<<'a'; // output will be something like: a538946288a
    

    另一方面,带有单个字符的单引号:

    cout << 'a'<<' '<<'a'; // output will be: a a
    

    如果你想给出多个空格字符,你可以使用双引号。

    在您的代码中:

    int main()
    {
    
        char c='x'; // c is character 'x'
        int i1=c;   // i1 is its integer value
        int i2='x'; // i2 has the integer value but it`s never used
    
        char c2 = i1; // c2 is the character 'x'
    
        cout << c <<" "<< i1 <<" "<<c2 << '\n';  // should print: x 120 x 
        // By using double quotes you may enter longer spaces between them 
        // vs. single quotes puts only a single space.
        return 0;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-01
      相关资源
      最近更新 更多