简体   繁体   English

输入和C ++中的字符

[英]Inputs along with characters in C++

I have been trying to write a prog which accepts college fees as input in the form Rs50000 and i would like to use only the integral part for the computation. 我一直在尝试编写一个编,它以Rs50000的形式接受大学费用作为输入,我只想使用积分部分进行计算。 How can i do that?? 我怎样才能做到这一点?? Is this possible?? 这可能吗??

#include<iostream>
using namespace std;
int main()
{
   int fee;
   cin >> Rs >> fee;
   return 0;
}

In order to read the string and process it as you've described, the following should work. 为了读取字符串并按照您的描述进行处理,应该执行以下操作。

std::string input;
std::cin >> input;
int fee = atoi(input.substr(2).c_str());

This code takes input from stdin. 此代码从stdin输入。 Then it parses the fee (3rd character to end) as an int. 然后它将费用(第3个字符结尾)解析为一个整数。 There are, of course, other ways to do this. 当然,还有其他方法可以做到这一点。 I am a fan of c_str() and atoi() because of a background in C, however a stringstream is just as capable. 由于C语言的背景,我是c_str()atoi()的爱好者,但是stringstream还是一样。

A note on your original code. 关于原始代码的注释。 It may be natural to think that you would stream in twice: 很自然地认为您会两次流式传输:
std::cin >> Rs >> fee; because one part is a string and the other is an int. 因为一部分是字符串,另一部分是整数。 However, std::cin streams are delimitated by whitespace. 但是, std::cin流由空格分隔。

Hope this helps! 希望这可以帮助!

Yes it's possible and there are lots of ways to do what you want, here's one way. 是的,这是可能的,并且有很多方法可以做您想要的事情,这是一种方法。 Take input as a string and remove "Rs" using substr(). 将输入作为字符串并使用substr()删除“ Rs”。 Then convert it to int. 然后将其转换为int。

#include <iostream>
#include <string>
#include <sstream>
using namespace std;

int main()
{
    stringstream stream;
    string amount,str;
    int fee;
    getline (cin, amount);
    str = amount.substr(2);
    stream << str;
    stream >> fee;

    cout << "Fee is : " << fee+1 << "\n"; //fee
    return 0;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM