Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

problems with cin and reading input in c++

i am new to c++ and i have a problem with cin in my code,when i run this code after i enter some words, it just skips and ignores second cin in the code and i dont understand it, i read that it happens because of enter and space in the new line and i should use cin.ignore but it still does not work.and for the first loop i use ctrl+z and loop ends my problem is after that

   int main() {
    vector<string> words;
    cout << "Enter your words" << endl;
    for (string input; cin >> input;) {
        words.push_back(input);
        cin.ignore();

    }
    cout << "You entered these words:" << endl;
    for (string a: words) {
        cout << a << endl;
    }
    cin.ignore();
    string disliked;
    cout << "If you have any disliked word please type it " << endl;
    cin >> disliked;
    for (int i = 0; i < words.size(); i++) {
        if (words[i] == disliked) {
                words[i] = "Bleep";
        }
    }
}

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

for (string input; cin >> input;) {
    words.push_back(input);
    cin.ignore();
}

So, as you say in a comment, the user ends this loop by entering end of file (ctrl-Z on Windows console). After that, the file is at end. You can not continue reading from it, it is closed.

You have to figure out some other way to end this first loop. Suggestions:

  • Instead of reading words, read lines usint std::getline, and if user enters empty line, then end this loop. You then have to split the line into words as a separate step, of course.
  • Add some specific non-letter "word" to mark the end of this loop, such as a lone ".".

Also, as long as you are reading words with std::cin >> word, you don’t need std::ignore() for anything. Reading into an std::string will skip any leading whitespace automatically.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading