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++

SHANG ZHOU
  • 57
  • 1
  • 7
  • 6
    Did you try anything? – AsthaUndefined Jan 28 '19 at 10:11
  • It's a *huge* learning curve (and certainly not for a C++ beginner), but I use Boost Spirit for this. – Bathsheba Jan 28 '19 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. – john Jan 28 '19 at 10:27
  • I had updated my question, sorry for this unclear issue. – SHANG ZHOU Jan 28 '19 at 10:31
  • just `scanf` it. – KamilCuk Jan 28 '19 at 10:36
  • 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? – Bathsheba Jan 28 '19 at 10:36
  • This feels kind of broad to me. It needs parsing, conversions, dynamic allocations. Are smart pointers allowed? – Galik Jan 28 '19 at 10:48
  • Maybe useful (from the C section): https://stackoverflow.com/questions/15472299/split-string-into-tokens-and-save-them-in-an-array and https://stackoverflow.com/questions/19093224/read-numbers-from-file-into-a-dynamically-allocated-array – Galik Jan 28 '19 at 11:06

1 Answers1

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;
}
Marek R
  • 32,568
  • 6
  • 55
  • 140