0

Query: Why getline() is not stopping for user input as per current code?

   // Program to find the word count in the string with input words array
        #include <iostream>
        #include <string>
        #include <map>
        #include <bits/stdc++.h>
        
        using namespace std;
  
        int main()
        {
            vector<string> arr;
            string individualString;
            string str;
            map<string, int> wordCount;
            map<string, int>::iterator itr;
            int numberofWords;

            cout << "Enter the number of words :" << endl;
            cin >> numberofWords;
        
            cout << "Enter the Words" << endl;
            for (int i = 0; i < numberofWords; i++)
            {
                cin >> individualString;
                arr.push_back(individualString);
            }
        
            cout << "Enter the String to be searched for Words" << endl;
            getline(cin, str);
        
            //wordCount = prepareWordsCountMap(arr, numberofWords);
        
            //wordCount = countWordsInString(str, wordCount);
        
            return 0;
        }

NOTE: If I move this

getline(cin, str);

just after all variable declarations, it works fine and accepts the input string from user.

  • 1
    You have to add `cin.ignore()` before the `getline()` statement. – Vector3 Jun 03 '22 at 14:57
  • Slight disagreement with above comment. Place the `ignore` after the transaction that leaves the unwanted items in the stream. A lot of the time this is the same place as before the `getline`, but when it isn't, 1) keeping the `ignore` with the reason you need it makes the code easier to read and 2) you may find, or later add, situations where the `ignore` is reached without unwanted data in the stream and data that needed to be processed is discarded. – user4581301 Jun 03 '22 at 15:17

0 Answers0