【问题标题】:How to get an input in c++ like "Ram:30,40,50,70"如何在 C++ 中获取输入,例如 \"Ram:30,40,50,70\"
【发布时间】:2022-11-04 00:20:15
【问题描述】:

在某些问题中,我在从用户那里获取输入时遇到问题,例如

ram:30,40,50    //string separated  string and comma separated integers
honda@30,tvs@30 //string and integer separated .
                  

我不知道如何获得该输入。

【问题讨论】:

标签: c++


【解决方案1】:

这个问题有很多潜在的解决方案。一个相当普遍的做法是:

  • 首先将一个完整的行读入一个字符串
  • 将字符串放入std::istringstream,这样你就可以使用io函数从那里提取数据
  • 使用带有分隔符的函数std::getlinestd::istringstream 中读取,直到看到分隔符
  • 再次执行相同的步骤以进一步拆分先前拆分的部分。

在第一种情况下,沿冒号拆分,然后沿逗号拆分 在第二种情况下,沿逗号拆分,然后沿“@”拆分结果部分

请阅读here 关于std::getline

一种潜在的解决方案可能如下所示:

#include <iostream>
#include <sstream>
#include <string>
#include <iomanip>
#include <vector>

std::istringstream test{ R"(ram:30,40,50
honda@30,tvs@30)" };

int main() {

    // Read a complete line
    std::string line{}; std::getline(test, line);

    // Put the line into a std::istringstream to extract further parts
    std::istringstream iss1(line);

    // Use std::getline to extract something until you see a separator
    std::string identifier{};
    std::getline(iss1 >> std::ws, identifier, ':');
    std::cout << identifier << '
';

    // Now extract all numbers
    std::string number{};
    while (std::getline(iss1 >> std::ws, number, ','))
        std::cout << number << '
';

    // Get the complete second string
    std::getline(test, line);

    // Split the string into parts until you see a comma
    std::vector<std::string> parts{};
    // Put the line into a std::istringstream to extract further parts
    std::istringstream iss2(line);

    while (std::getline(iss2 >> std::ws, identifier, ','))
        parts.push_back(identifier);

    // Now all parts are stored in a vector
    // Then let us split the single parts further
    for (const std::string& part : parts) {
        std::cout << '
';
        std::istringstream iss3(part);

        std::getline(iss3, identifier, '@');
        std::cout << identifier << '
';

        std::getline(iss3, number);
        std::cout << number << '
';
    }
}

还有更高级的技术,但现在,请尝试理解以上内容。

【讨论】:

    猜你喜欢
    • 2011-12-19
    • 2020-09-17
    • 1970-01-01
    • 1970-01-01
    • 2023-03-29
    • 2012-12-23
    • 2022-07-02
    • 2018-01-24
    • 1970-01-01
    相关资源
    最近更新 更多