【问题标题】:Simple c++ input fuction简单的c++输入函数
【发布时间】:2015-04-14 07:23:05
【问题描述】:

我是 C++ 新手,我想知道程序是否要求您输入分数 (a/b),您如何删除除号 ("/") 以获得 a 和 b 的值?

例如:

int x1, x2, y1, y2;
cout << "The programk performs arithmetic operations on two rational numbers." << endl;
cout << "Enter a rational number <a/b> : ";
cin >> // what can i do to get the value of a for x1 and b for x2??

感谢您的宝贵时间,我们将不胜感激。

【问题讨论】:

  • 读取一个字符并忽略它。

标签: c++ string integer


【解决方案1】:

你可以试试:

#include <iostream>
#include <vector>
#include <sstream>

std::vector<std::string> Split(const std::string &s, char delim)
{
    std::vector<std::string> elems;
    std::stringstream ss(s);
    std::string item;
    while (std::getline(ss, item, delim))
        elems.push_back(item);
    return elems;
}

int main() 
{
    std::cout << "Enter a/b:" << std::endl;
    std::string input;
    std::cin >> input;
    auto ab = Split(input, '/');
    int a = std::stoi(ab[0]);
    int b = std::stoi(ab[1]);
    std::cout << a << "/" << b << std::endl;
    return 0;
}

【讨论】:

    【解决方案2】:

    使用 indexOf 查找“/”的位置,并为左侧部分创建一个子字符串,为右侧部分创建一个子字符串。然后你可以将左右部分解析为数字,并计算结果。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-07
      • 1970-01-01
      相关资源
      最近更新 更多