D
D
Dmitry Shevchenko2021-12-16 09:09:20
C++ / C#
Dmitry Shevchenko, 2021-12-16 09:09:20

Selecting text between two commas C++?

There is an input string with two commas. I find the positions of two commas and divide into 3 substrings by commas, but the substring between two commas is not determined correctly.

#include <iostream>
#include <string>
using namespace std;
string stroke;
int n;

int main()
{

  cin >> n;
  if (n > 10000 || n < 1) {
    return -1;
  }
  cin.ignore();
  for (int i = 1; i <= n; i++) {
    getline(cin, stroke);
    cout <<"string: "<< stroke << endl;
    //деление строки на персон :
    short zap1 = stroke.find(",");
    short zap2 = stroke.find(",",zap1+1);
    cout << "zap2 : " << zap2 << endl;
    string dad, mom, son;
    dad = stroke.substr(0, zap1);
    mom = stroke.substr(zap1 + 1, zap2);
    son = stroke.substr(zap2 + 1);
    cout << "son : "<<son << "  moth : "<<mom<<"  dad : " << dad <<endl;
      

  }
  
}

I get a string from the first comma to the end, although everything else is defined correctly.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
res2001, 2021-12-16
@ZER0x32

Because the second parameter in substr is not the end position, but the number of characters. Feel the difference.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question