Read String Till Flag(C ++)

时间:2017-08-02 05:14:46

标签: c++ string cin

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

e.g。 “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 ++中执行此操作的最佳方法是什么?

此外,验证输入以转换为整数并测试值范围的最佳方法是什么?

4 个答案:

答案 0 :(得分:1)

如果字符串中只有一个逗号分隔符,您可以在输入和子字符串输入中找到逗号首先出现的位置。

请尝试以下操作:

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

答案 1 :(得分:1)

最简单的方法是让operator>>为您完成所有工作:

int xCoor, yCoor;
char ch;

cout << "Input coordinates: ";

if (cin >> xCoor >> ch >> yCoor)
{
    // use coordinates as needed ...
}
else
{
    // bad input... 
}

答案 2 :(得分:0)

您可以通过指定分隔符并解析字符串

来完成此操作
std::string delimiter = ",";

size_t pos = 0;
std::string token;
while ((pos = coorPair.find(delimiter)) != std::string::npos) {
    token = coorPair.substr(0, pos);
    std::cout << token << std::endl;
    coorPair.erase(0, pos + delimiter.length());
}

std::cout << coorPair << endl;

{5,6} {6}中的最后一个标记示例将在coorPair中。

另一种方法是使用评论中指出的std::getline

std::string token; 
while (std::getline(coorPair, token, ',')) 
{ 
    std::cout << token << std::endl; 
}

答案 3 :(得分:0)

http://www.cplusplus.com/reference/string/string/getline/

我建议使用getline()。

以下是我如何使用它的一个小例子。它接受来自流的输入,因此您可以使用ifstream作为输入,或者执行下面的操作并将字符串转换为流。

// input data
std::string data("4,5,6,7,8,9");

// convert string "data" to a stream
std::istringstream d(data);

// output string of getline()
std::string val;

std::string x;
std::string y;
bool isX = true;

char delim = ',';

// this will read everything up to delim
while (getline(d, val, delim)) {
    if (isX) {
        x = val;
    }
    else {
        y = val;
    }
    // alternate between assigning to X and assigning to Y
    isX = !isX;
}