我正在读取用户输入的 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/