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];

}
7
  • 2
    This declaration std::string(*ptr)[50] = &list; does not make a sense. Commented Sep 15, 2021 at 7:50
  • 2
    You should have also a counter for word, (*ptr)[i] = value place the word at the ith place currently (where the comma is). Commented Sep 15, 2021 at 7:50
  • This is exactly what you want: stackoverflow.com/questions/14265581/… Commented Sep 15, 2021 at 7:56
  • std::vector<std::string> Seperate(std::string input, char sep = ', '); would be a better interface. Commented Sep 15, 2021 at 7: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 Commented Sep 15, 2021 at 8:01

1 Answer 1

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 = "";
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.