代码之家  ›  专栏  ›  技术社区  ›  user6336941

读取字符串直到标志(C++)

  •  0
  • user6336941  · 技术社区  · 8 年前

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

    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. 
    // ?
    

    在C++中实现这一点的最佳方法是什么?

    4 回复  |  直到 7 年前
        1
  •  1
  •   suhdonghwi    8 年前

    尝试以下操作:

    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
    
        2
  •  1
  •   Remy Lebeau    8 年前

    operator>> 为您完成所有工作:

    int xCoor, yCoor;
    char ch;
    
    cout << "Input coordinates: ";
    
    if (cin >> xCoor >> ch >> yCoor)
    {
        // use coordinates as needed ...
    }
    else
    {
        // bad input... 
    }
    
        3
  •  0
  •   Samer Tufail    8 年前

    可以通过指定分隔符并解析字符串来实现这一点

    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; 
    }
    
        4
  •  0
  •   blake    8 年前

    http://www.cplusplus.com/reference/string/string/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;
    }