简体   繁体   中英

C++, issue with using getline and cin.ignore() in for loop.Getline is skipping by second iterate in the for loop

I have been trying to figure out why it doesn't read my second getline(). The first getline(cin, line) works fine. No errors or anything. it just skips that line by the second iterate in the loop. Any help will be greatly appreciated. Thank you.

    int main() {
    
        int n = 0;
        std::cin >> n;
        std::vector <int> arrNumbers;
        int requestLine = 0;
        std::string line;
        double procent = 0;
    
        if (n > 99) {
            std::cout << "wrong range of number" << std::endl;
            exit(-1);
        }
    
        for (int i = 0; i < n; i++) {
            int num;
            std::cin >> num;
            arrNumbers.push_back(num);
        }
    
        std::cin >> requestLine;
        for (int i = 0; i < requestLine; i++) {
    
            std::cin.ignore(256, '\n');
            std::getline(std::cin, line);
                    
            
            int del1 = line.find_first_of(' ', 0);  // first position of space
            int del2 = line.find_first_of(' ', del1 + 1); // second position of space
    
            std::stringstream indexStr(line.substr(0, del1)); // position
            std::stringstream numberStr(line.substr(del1, del2)); // number
            std::stringstream repeatsStr(line.substr(del2)); // repied
    
            int index, number, repeats;
    
            indexStr >> index; 
            numberStr >> number; 
            repeatsStr >> repeats;
    
            arrNumbers.insert(arrNumbers.begin() + index - 1, repeats, number);
    
            del1 = 0;
            del2 = 0;
            
            
        }
    
        for (const int& number: arrNumbers) {
            sort(arrNumbers.begin(), arrNumbers.end());
        }
    
        
        return 0;
    }

Did you verify that the program came inside the loop? Check the value of “n” just before it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM