【问题标题】:Read String Till Flag (C++)读取字符串直到标志 (C++)
【发布时间】:2017-10-17 05:50:27
【问题描述】:

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

例如"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++ 中最好的方法是什么?

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

【问题讨论】:

标签: c++ string cin


【解决方案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

【讨论】:

  • 谢谢,效果很好。我只需要用 coorPair.substr 交换 pos.substr
  • @user6336941 糟糕,我的错。
【解决方案2】:

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

int xCoor, yCoor;
char ch;

cout << "Input coordinates: ";

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

【讨论】:

    【解决方案3】:

    您可以通过指定分隔符并解析字符串来做到这一点

    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 中。

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

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

    【讨论】:

    • 使用std::getline()',' 作为分隔符会更容易。
    • 可以,我认为 OP 对“解析”感兴趣。
    • 它还在解析,只是让STL帮助,例如:std::string token; while (std::getline(coorPair, token, ',')) { std::cout &lt;&lt; token &lt;&lt; std::endl; }
    【解决方案4】:

    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;
    }
    

    【讨论】:

      猜你喜欢
      • 2014-07-06
      • 1970-01-01
      • 2021-02-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-12-19
      • 2014-05-09
      相关资源
      最近更新 更多