Home > database >  problems with cin and reading input in c
problems with cin and reading input in c

Time:07-25

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";
        }
    }
}

CodePudding user response:

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.

  • Related