Fast and efficient way to read a space separated file of numbers into an array?

后端 未结 7 543
情话喂你
情话喂你 2021-01-21 03:42

I need a fast and efficient method to read a space separated file with numbers into an array. The files are formatted this way:

4 6
1 2 3 4 5 6
2 5 4 3 21111 101         


        
相关标签:
7条回答
  • 2021-01-21 04:29

    Read the file a character at a time. If it's whitespace, start a new number. If it's a digit, use it.

    for numbers with multiple digits, keep a counter variable:

    int counter = 0;
    while (fileOpen) {
        char ch = readChar(); // use your imagination to define this method.
        if (isDigit(ch)) {
            counter *= 10;
            counter += asciiToDecimal(ch);
        } else if (isWhitespace(ch)) {
            appendToArray(counter);
            counter = 0;
        } else {
            // Error?
        }
    }
    

    Edited for clarification.

    0 讨论(0)
提交回复
热议问题