【问题标题】:c++ char to int from user inputc ++ char从用户输入到int
【发布时间】:2014-03-09 19:42:19
【问题描述】:

我正在读取用户输入的 2 个坐标,如下所示:

输入坐标:10 5

我希望能够将 10 读取为行,将 5 读取为列。

这就是我所拥有的。

  char coord[5];

  ...

  cout << "Enter a coord: ";
  cin.getline(coord,sizeof(coord));
  row = atoi(coord[0]);

所以代码在 atoi() 上给了我一个错误,如果用户输入像 10 char 这样的数字无法真正从索引中读取它,你们会怎么做呢?谢谢。

【问题讨论】:

    标签: c++ string int


    【解决方案1】:

    好吧,您实际上可以使用ints 来表示您的坐标变量并像这样读取它们:

    int row;
    int column;
    std::cout << "Enter a coord: ";
    std::cin >> row >> column;
    std::cout << "Coords: " << row << " " << column << std::endl;
    

    由于您的错误:您在atoi 上收到错误,因为它以const char *str 作为参数,并且当您使用字符数组时,您需要像int row = atoi(coord); // which will read only the first value 一样传递它,因为数组是implicity converted a pointer to the first array element(通常说“衰减”为指针,因为这样您就无法在项目上调用 sizeof())当以这种方式传递给函数时。

    【讨论】:

      猜你喜欢
      • 2014-12-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-30
      • 2013-09-02
      • 1970-01-01
      • 2014-04-26
      • 2016-08-27
      相关资源
      最近更新 更多