1

How do I split a string input into two different ints?

I am writing a program to input two different fractions (like 2/3) and am wanting to read in the 2/3 as a string and split it by a delimiter (the /).

Example:

Input: 2/3
Values:
int num = 2;
int denom = 3;

Example 2:

Input: 11/5
Values:
int num = 11;
int denom = 5;

Thanks!

3
  • Well you can do: stackoverflow.com/questions/14265581/… to split the string and you can do stackoverflow.com/questions/194465/… to convert the strings to an int. Commented Apr 5, 2017 at 16:06
  • For simple tasks you can do this int a, b; char c; std::cin >> a >> c >> b; Commented Apr 5, 2017 at 16:09
  • I forgot to add that you can use stringstream object instead cin Commented Apr 5, 2017 at 16:16

2 Answers 2

1

For something quite simple like "2/3" you could use string.find and string.substr

string.find will return the position in your string that the '/' character resides. You can then use string.substr to split the string both before and after the '/' character. Don't have time to write a code example but if you're really stuck, PM me and I'll knock something up when I get home.

Sign up to request clarification or add additional context in comments.

Comments

0

Run the following with the -std=c++ 11 flag specified if using g++.

#include <iostream>
#include <string>

void find_num_denom(int& num, int& denom, std::string input) {
    int slash_index = input.find("/");
    num = std::stoi(input.substr(0, slash_index));
    denom = std::stoi(input.substr(slash_index + 1, input.length()));
}

int main() {
    int n,d;
    find_num_denom(n, d, "23/52");
    std::cout<<n<<"  "<<d<<"\n";
    return 0;
}

this returns 23 52 for me. Let me know if you have any problems

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.