c++ - 读取字符串直到标记 (C++)

标签 c++ string cin

我正在尝试读取一个字符串,直到到达“,”字符,然后将读取的内容存储在一个新字符串中。

例如“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/

相关文章:

python - 如果字符串中的单词位于单词列表中,则替换该单词

c++ - 我可以在 C++ 中通过 operator[] 正确设置 std::vector 的第 n 个值吗?

c++ - Makefile:将对象编译到不同的目录并从那里构建

c++ - 用于检查 C++ 方法的 `noexcept` 属性的单元测试

c++ - 有没有更好的方法来解决这个问题 - Programming Principles & Practices Using C++ : Ch. 4 - Drill?

python - 将数字字符串编码为缩短的字母数字字符串,然后再返回

string - 如何在 tcl 中执行子字符串提取和替换

c++ - scanf在c++中的表示是什么

c++ - 如何将 "Dummy"值替换为 std::cin?

c++ - 如何在不使用 getline() 的情况下接受不同行中的整数输入值?