从用户输入c ++ char到int

use*_*379 2 c++ string int

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

输入坐标:10 5

我希望能够在10中读取行,将5作为列.

这就是我所拥有的.

  char coord[5];

  ...

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

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

Nat*_*pel 5

那么,您实际上可以使用ints来表示坐标变量,并按如下方式读取它们:

int row;
int column;
std::cout << "Enter a coord: ";
std::cin >> row >> column;
std::cout << "Coords: " << row << " " << column << std::endl;
Run Code Online (Sandbox Code Playgroud)

从你的错误:你得到一个错误atoi因为它得到一个const char *stras参数,并且你正在使用一个char数组,你需要传递它int row = atoi(coord); // which will read only the first value,因为数组是隐含转换指针到第一个数组元素(通常说sizeof()当以这种方式传递给函数时,"衰减"到指针,因为你失去了调用项目的能力.