Home > Blockchain >  Problems with cin and reading input
Problems with cin and reading input

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 the second cin in the code and I don't understand why.

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. For the first loop, I use Ctrl Z and loop ends my problem 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