简单的c++输入函数
Simple c++ input fuction
我是 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??
感谢您抽出宝贵时间,我们将不胜感激。
使用 indexOf 查找“/”所在的位置,并为左侧部分创建一个子字符串,为右侧部分创建一个子字符串。然后就可以将左右部分解析为数字,计算结果。
你可以试试:
#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;
}
我是 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??
感谢您抽出宝贵时间,我们将不胜感激。
使用 indexOf 查找“/”所在的位置,并为左侧部分创建一个子字符串,为右侧部分创建一个子字符串。然后就可以将左右部分解析为数字,计算结果。
你可以试试:
#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;
}