0

I have a list formatted like - String : Int, how would i seperate each one into individual strings?

I can't seem to figure out the separation part where it reads one space before the colon and one space after.

  • try [std::string::find](https://en.cppreference.com/w/cpp/string/basic_string/find) and [std::string::substr](https://en.cppreference.com/w/cpp/string/basic_string/substr) – Leonid Apr 12 '20 at 13:44

2 Answers2

0

If I'm understanding right, you can read the file line by line, then separate the two elements you want with strtok() (if you're using null-terminated byte strings) or a combination of find() and substr() (if you're using std::strings)

I've worked with the former, so I'll explain what I'd do.

first, I'll read the whole line to a char array:

    #include <cstring>
    char temp[256];
    cin.getline(temp, 256);

then, with strtok I split the line into what you need

    char str[256], num[256]
    char *p = strtok(temp, ":");
    strcpy(str, p);
    p = strtok(NULL, ":");
    strcpy(num, p);

Make sure to change cin to whatever your file variable is named.

  • Shouldn't you use `strncpy` instead of `strcpy`? See https://stackoverflow.com/questions/1258550/why-should-you-use-strncpy-instead-of-strcpy. Edit: `strlcopy()` might be better / safer. – darclander Apr 12 '20 at 14:04
0
string aStr;
char split;
int aInt;

while (ifs >> aStr >> split >> aInt) {
    // Dealing with these variables
}

Hope it helps

AlpacaMax
  • 388
  • 3
  • 10