C++ 从用户输入中将char转换为int

标签 c++ string int

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

输入坐标:10 5

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

这就是我所拥有的。

  char coord[5];

  ...

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

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

最佳答案

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

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

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

关于C++ 从用户输入中将char转换为int,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22287176/

相关文章:

c++ - "::functionName()"在 C++ 中意味着什么?

java - 为计算器拆分输入字符串

javascript - 尚未在字符串中声明变量

java - 如何将 int 转换为 byte[]?

c++ - 嵌套并行 for 循环 : "Parallel outer for loop" in "parallel inner for loop as a function"

c++ - cout 没有输出正确的数据

c - 文件描述符 : troubles in storing a read int value into a variable

int - Kotlin 数据类 Gson 序列化问题

c++ - 循环显示一个数字增加 0.2% 5 次

php - 在 PHP 中从字符串中提取 DOM 元素