【问题标题】:How to access c++ string by index for a integer number?如何通过索引访问整数的c ++字符串?
【发布时间】:2022-01-19 15:48:46
【问题描述】:

我如何编辑这个程序让 j 包含“1”?

目前它显示 49,这是我认为的 ascii 值。

#include <iostream>
using namespace std;

main()
{
  string i = "123";
  int j = i[0];
  cout << j;
}

【问题讨论】:

  • 仅供参考,首先,您包括 &lt;string&gt; ,这是将 std::string 带到您的 C++ 聚会的合同授权。如果没有它就“起作用”,那是偶然的;不是设计,工程师也不喜欢偶然编码。
  • 只需从j 中减去'0'
  • @WhozCraig 根据stackoverflow.com/a/16506109 的评论,std::string 必须完全定义,即使您只包含了&lt;iostream&gt;。但是,我同意您仍然应该包含 &lt;string&gt;,这样您就不会意外调用仅在 &lt;string&gt; 中定义的非成员函数

标签: c++


【解决方案1】:

您可以如下图所示:

int main()
{
  std::string i = "123";
  int j = i[0] - '0'; //this is the important statement
  std::cout << j;
}

说明

'0'character literal

所以当我写的时候:

int j = i[0] - '0';

根本原因i[0] - '0' 为何/如何工作是通过promotion。 特别是,

i[0]'0' 都将升级为 int。而用于初始化变量j左侧的最终结果将是这两个promoted@的减法的结果987654332@ 右侧的值。

标准 C++保证结果是整数 1,因为来自 C++ Standard (2.3 Character sets)

  1. ...在源和执行基本字符集中,值 上述十进制数字列表中 0 之后的每个字符应为 比前一个值大一。

所以不需要使用48等幻数。

【讨论】:

    【解决方案2】:
    1. 从字符构造一个新字符串。
    2. 将子字符串转换为整数。 示例:
    #include <iostream>
    using namespace std;
    
    main() {
      string i = "123";
    
      // Method 1, use constructor
      string s1(1, i[0]);
      cout << s1 << endl;
    
      // Method 2, use convertor
      int j = atoi(s1.c_str());
      cout << j << endl;
    }
    

    【讨论】:

    • 方法 2 要好得多,但问题是只获取第一个数字而不是整个数字。
    • @AshutoshRaghuwanshi 两种方法都得到相同的结果。我在发布之前已经对它们进行了测试。
    【解决方案3】:

    解决方案很简单,只需将 j 转换为 char 即可。 示例:

    #include <iostream>
    using namespace std;
    
    main()
    {
      string i = "123";
      int j = i[0];
      cout << char(j);
    }
    

    【讨论】:

      【解决方案4】:

      你必须从字符数字中减去 ASCII '0' (48):

      #include <iostream>
      using namespace std;
      
      int main()
      {
        string i = "123";
        int j = i[0] - 48;  // ASCII for '0' is 48
        // or
        // int j = i[0] - '0';
        cout << j;
      }
      

      【讨论】:

      • 字符 '0'any 编码的正确字符数字,而不仅仅是 ASCII。使用幻数 48 将强制使用 ASCII,而 '0' 可移植到任何 C++ 实现。
      • @Someprogrammerdude,不知道这一点。感谢会进行编辑。
      【解决方案5】:

      j 更改为char 而不是int

      #include <iostream>
      #include <string>
      using namespace std;
      
      int main()
      {
        string i = "123";
        char j = i[0];
        cout << j;
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-11-08
        • 2012-05-13
        • 1970-01-01
        • 1970-01-01
        • 2013-01-15
        • 1970-01-01
        • 1970-01-01
        • 2010-09-05
        相关资源
        最近更新 更多