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!

MarianD
  • 9,720
  • 8
  • 27
  • 44
  • Well you can do: http://stackoverflow.com/questions/14265581/parse-split-a-string-in-c-using-string-delimiter-standard-c to split the string and you can do http://stackoverflow.com/questions/194465/how-to-parse-a-string-to-an-int-in-c to convert the strings to an int. – AresCaelum Apr 05 '17 at 16:06
  • For simple tasks you can do this `int a, b; char c; std::cin >> a >> c >> b;` – Logman Apr 05 '17 at 16:09
  • I forgot to add that you can use `stringstream` object instead `cin` – Logman Apr 05 '17 at 16:16

2 Answers2

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.

Catch_0x16
  • 167
  • 4
  • 11
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

Srini
  • 1,536
  • 1
  • 18
  • 32