D
D
Dmitry Shevchenko2021-11-25 11:02:15
C++ / C#
Dmitry Shevchenko, 2021-11-25 11:02:15

Splitting string into 2 parts and converting to int?

for (int i = 1; i <= k; i++) {
    getline(file, text);
    cout << "1 part '" << text.substr(0, text.find('/')) << "'  sec  part '" << text.substr(text.find('/') + 1)<<"'" << endl;
    day += stoi(text.substr(0,text.find("/")).c_str())- 48 + stoi (text.substr(text.find("/")+1).c_str()) - 48;
    cout << "day " << day << endl;
  }

I have a string like dd/mm at the input, and the first digit can be zero. I'm trying to select a substring, but nothing happens, because find doesn't find "/" and returns a huge value. I don't know what to do, because I'm just learning the language, but I don't have much time.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alex Khayev, 2021-11-25
@hasalex

in general like this:

std::string str = "00/34";
    std::string::size_type slash = str.find("/");
    if (slash != std::string::npos) {
      int num1 = atoi(str.substr(0, slash-1).c_str());
      int num2 = atoi(str.substr(slash+1).c_str());
    
      cout<<"Num1: " << num1 << ", Num2: " << num2;
    }

Only there are no checks for edge cases (when there is no number before or after the slash, when there is not a number, etc.)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question