我正在尝试读取一个字符串,直到到达“,”字符,然后将读取的内容存储在一个新字符串中。
例如“5,6”
// Initialise variables.
string coorPair, xCoor, yCoor
// Ask to enter coordinates.
cout << "Input coordinates: ";
// Store coordinates.
cin >> coorPair
// Break coordinates into x and y variables and convert to integers.
// ?
我还需要将 y 值存储在一个单独的变量中。
在 C++ 中执行此操作的最佳方法是什么?
此外,验证输入以转换为整数并测试值范围的最佳方法是什么?
最佳答案
如果字符串中只有一个逗号分隔符,则可以只查找逗号在输入中第一个出现的位置和找到位置的子字符串输入。
尝试以下操作:
std::size_t pos = coorPair.find_first_of(","); //Find position of ','
xCoor = coorPair.substr(0, pos); //Substring x position string
yCoor = coorPair.substr(pos + 1); //Substring y position string
int xCoorInt = std::stoi(xCoor); //Convert x pos string to int
int yCoorInt = std::stoi(yCoor); //Convert y pos string to int
关于c++ - 读取字符串直到标记 (C++),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45451986/