0

I have a string from command line input, like this:

string input = cmd_line.get_arg("-i"); // Filepath for offline mode

This looks like a file as below:

input = "../../dataPosition180.csv"

I want to extract out the 180 and store as an int.

In python, I would just do:

data = int(input.split('Position')[-1].split('.csv')[0])

How do I replicate this in C++?

John Kugelman
  • 349,597
  • 67
  • 533
  • 578
connor449
  • 1,549
  • 2
  • 18
  • 49
  • 1
    [Find](https://en.cppreference.com/w/cpp/algorithm/find) the first [digit](https://en.cppreference.com/w/cpp/string/byte/isdigit), then use [`std::stoi`](https://en.cppreference.com/w/cpp/string/basic_string/stol) to convert the number. – Some programmer dude Apr 29 '21 at 14:48
  • Or use a regex: https://stackoverflow.com/questions/30073839/c-extract-number-from-the-middle-of-a-string – user1810087 Apr 29 '21 at 14:49
  • 1
    What exactly does `180` represent here? I.e. in hypothetical example of path being `../45/123/4data25Position180_1.csv` what would be the number you are looking for? – SergeyA Apr 29 '21 at 14:51
  • @SergeyA that won't happen. It will only be as specified in the post. – connor449 Apr 29 '21 at 14:54
  • 1
    Than just follow @Someprogrammerdude suggestion. – SergeyA Apr 29 '21 at 14:55
  • @Someprogrammerdude can you provide example? – connor449 Apr 29 '21 at 14:57

2 Answers2

1

Here's a (somewhat verbose) solution:

#include <string>
#include <iostream>

using namespace std;

int main() {
  string input = "../../dataPosition180.csv";
  // We add 8 because we want the position after "Position", which has length 8.
  int start = input.rfind("Position") + 8;
  int end = input.find(".csv");
  int length = end - start;
  int part = atoi(input.substr(start, length).c_str());
  cout << part << endl;
  return 0;
}
Marcelo Menegali
  • 866
  • 1
  • 5
  • 5
0
#include <string>
#include <regex>

using namespace std;

int getDataPositionId (const string& input){
    regex mask ("dataPosition(\\d+).csv");
    smatch match;    
    if (! regex_search(input, match, mask)){
        throw runtime_error("invalid input");
    }
    return std::stoi(match[1].str());
}
Daniel Zin
  • 479
  • 2
  • 7