【问题标题】:How to get second or third 'part' of user input? C++如何获得用户输入的第二或第三“部分”? C++
【发布时间】:2015-10-25 05:10:43
【问题描述】:

用户输入是:

0 1 4 5

如何获取 0 并将其保存为整数,那么如何获取 4 并将其保存为整数?

情况2:

用户输入是:

0B11B3B76B

如何将它们(单独)保存到数组(字符串类型)中?

我知道对于你们中的一些人来说这是一个简单的问题,但那是我接触 C++ 的第一天,我必须完成这件事。 .NET 永远!

【问题讨论】:

  • 向我们展示您的尝试。
  • 查看std::cin 并使用int 类型和std::string 类型。
  • 是的,std:cin,但它会保存整个 0 1 4 5,但我只想要 ex。 4. 那是我不知道的。

标签: c++ iostream


【解决方案1】:

您必须遍历输入字符串的每个字节,提取每个数字并将其作为整数转换为数组,如果您知道输入字符串的大小或字符串是固定的或具有最大值,这将有所帮助长度。

类似:

char myStr[12] = "0123456789";

int myArray[12];
int intCh;

for (intCh = 0; intCh < 12; intCh++) {
   /* Look for the \0 byte that terminates the string. */
   if (myStr[intCh] == '\0')
       break;

   /* We need to cast the char to an int as we store it in the
    * array something like this.
    */
   myArray[intCh] = (int) myStr[intCh];
}

希望对您有所帮助,我已经有一段时间没有使用 C 或 C++ 编写代码了,但它应该能给您一些指导……嘿,明白了吗?指针!

祝你好运。

补充一下,你的问题让我有点困惑,因为你打开说你想将 int 转换为 char,然后你说你想做相反的事情并将整数类型转换为字符串。

为此,您将使用相反的方法,您将获取整数数组的成员并将它们转换为 (char) 赋值:

myStr[intCh] = (char) myArray[intCh];

或者类似的东西;)

【讨论】:

    猜你喜欢
    • 2015-08-13
    • 2022-11-30
    • 1970-01-01
    • 2021-11-05
    • 2014-09-02
    • 2019-02-12
    • 1970-01-01
    • 2019-06-02
    • 1970-01-01
    相关资源
    最近更新 更多