简体   繁体   中英

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. 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. Then it parses the fee (3rd character to end) as an int. 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.

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.

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(). Then convert it to 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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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