0

I am making a program which asks user for input and then separates it from comma and adds all separated values to an array. But as you can see, when I print the first value of the array, it doesnt print anything. Im a beginner.

#include <iostream>
#include <string>
#include "Header.h"
#include "Windows.h"
#include <array>
 
void Seperate(std::string input, std::string(*ptr)[50]) {

    if (input[input.length() - 1] == ',')
    {
        input.erase(input.length() - 1, 1);
    }

    std::string value;
    int length = input.length();
    for (int i = 0; i < length; i++) {
        if (input[i] != ',') {
            value += input[i];
        }
        else {
            (*ptr)[i] = value;
            value = "";
        }
    }

}
int main() {
    std::cout << "Enter comma seperated values to seperate: ";
    std::string input;
    std::cin >> input;
    std::string list[50];
    std::string(*ptr)[50] = &list;
    Seperate(input, ptr);
    std::cout << list[0];

}
ihsan
  • 365
  • 3
  • 11
  • 2
    This declaration std::string(*ptr)[50] = &list; does not make a sense. – Vlad from Moscow Sep 15 '21 at 07:50
  • 2
    You should have also a counter for word, `(*ptr)[i] = value` place the word at the `i`th place currently (where the comma is). – Jarod42 Sep 15 '21 at 07:50
  • This is exactly what you want: https://stackoverflow.com/questions/14265581/parse-split-a-string-in-c-using-string-delimiter-standard-c – Raffallo Sep 15 '21 at 07:56
  • `std::vector Seperate(std::string input, char sep = ', ');` would be a better interface. – Jarod42 Sep 15 '21 at 07:57
  • Are you aware that if you read into a string reading stops on first white-space occurring. So `a, b, c` would read in only `a,`. If you want to be able to cope with spaces you might be interested in [std::getline](https://en.cppreference.com/w/cpp/string/basic_string/getline) – Aconcagua Sep 15 '21 at 08:01
  • @Aconcagua yes i know that i was just worried why this wasn't working. – ihsan Sep 15 '21 at 08:02
  • Side note: you are only outputting first element of the list, you might instead run in a loop over all elements until you find the empty string. – Aconcagua Sep 15 '21 at 08:03

1 Answers1

2

On this part you should use another int value to set your pointer values :

else {
        (*ptr)[i] = value;
        value = "";
    }

This should work for you like this :

std::string value;
int length = input.length();
int j = 0;
for (int i = 0; i < length; i++) {
    if (input[i] != ',') {
        value += input[i];
    }
    else {
        (*ptr)[j] = value;
        j = j + 1;
        value = "";
    }
}
Prog_is_life
  • 754
  • 1
  • 5
  • 15