0

I am new to c++.My aim is to read a file containing all integers, like

1 2 3\n 1 3 4\n 1 2 4\n

and

1,2 3,4 5,6\n 1,3 3,4 3,5\n 1,3 3,4 4,2\n

I could use getline to read them, but how could I split it into an integer array. Like array[3]={1,2,3} and array2={1,2,3,4,5,6} for the first line reading result? Sorry I forgot to mention that I was trying to not use the STLs for C++

8
  • 6
    Did you try anything? Commented Jan 28, 2019 at 10:11
  • It's a huge learning curve (and certainly not for a C++ beginner), but I use Boost Spirit for this. Commented Jan 28, 2019 at 10:16
  • You should add that you're 'trying' not to use the STL otherwise you're just going to get more answers using the STL. Which of course is the easy way to do this. Commented Jan 28, 2019 at 10:27
  • I had updated my question, sorry for this unclear issue. Commented Jan 28, 2019 at 10:31
  • 6
    What do you have against the C++ Standard Library? Despite my first comment (which would be a one-liner once you set the grammar up), using std::vector would give you a good solution. Why not write the whole thing in assembler to make your life even more unpleasant? Commented Jan 28, 2019 at 10:36

1 Answer 1

0

You can do it without boost spirit

// for single line:
std::vector<int> readMagicInts(std::istream &input)
{
    std::vector<int> result;

    int x;
    while(true) {
       if (!(input >> x)) {
           char separator;
           input.clear(); // clear error flags;
           if (!(input >> separator >> x)) break;
           if (separator != ',') break;
       }
       result.push_back(x);
    }

    return result;
}

std::vector<std::vector<int>> readMagicLinesWithInts(std::istream &input)
{
    std::vector<std::vector<int>> result;

    std::string line;
    while (std::getline(input, line)) {
        std::istringstream lineData(line);
        result.push_back(readMagicInts(lineData));
    }
    return result;
}
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.