jeudi 16 septembre 2021

istringstream skipping over middle input c++

I am in the process of making an AVL tree with insertion (denoted A) and deletion (denoted D). For example, if the user inputs A1 A2 A3 PRE, the keys 1, 2, and 3 will be inserted and then printed in pre-order. If the user inputs A22 D22 A3 POST, the key 22 will be inserted then deleted, and the key 3 will be inserted and printed in post-order notation.

In trying to separate the chars (A, D) from the integers, I have used an istringstream. However, for some reason, it is skipping over the middle entry. Below is the relevant code:

// Get the first character of each vector element char ops ; // max 100 inputs istringstream ss(input) ; string operation ; vector integers ; // integers to be inserted/deleted

while (ss >> ops && !ss.eof()){
    if (ops == 'A' || ops == 'D') operation += ops ;

    if (!ss.fail()){
        for (int nums; ss >> nums;) integers.push_back(nums) ;
    }

    if (ss.fail())
    {
        ss.clear() ;
        string token ;
        ss >> token ;
        cout << "token: " << token << " " ; // testing
    }
}

cout << endl ;

// print
for (int i = 0; i < integers.size(); i++) cout << integers.at(i) << " " ;
    cout << endl ;

For input: A1 A2 A3 PRE Output: token: A2 token: PRE 1 3

It is filtering out the A2 (middle) and discarding - I am unsure how to fix this.

I have also written code for inputting and filtering each element into a separate string element, but trying to separate this out is a nightmare:

// Initialise input string string input ;

// Get input
getline(cin, input) ;

// Separate each input into string elements
// Use size_t instead of int since dealing with memory ranges
size_t start = 0 ;
size_t space = input.find_first_of(" ") ;
string filtered ;
vector<int> n ; // vector of sizes of each input number
unsigned int len = 0 ;

while(space != string::npos){

    // If space > start, a word has been filtered - store as string element
    if (space > start){
        if (start == 0){
            len = space - start - 1 ;
            if (len == 1) filtered += input[start + 1] ;
        }
        else {
            if (len == 1) filtered += input[start + 2] ;
            else filtered += input.substr(start + 1, start + len) ;
            len = space - start - 2 ;
        }
    }
    n.push_back(len) ;

    start = space++ ;
    space = input.find_first_of(" ", space) ;
}

// Determine how to print (pre, post, or in-order)
string print = input.substr(start + 1, input.length()) ;

Aucun commentaire:

Enregistrer un commentaire