1

can you help me Why this code can't be swap

    cout << "Enter a string: ";
    getline(cin, str1);

    cout << "Enter another string: ";
    cin.get(str, 100, '\n');

Into

    cout << "Enter  string: ";
    cin.get(str, 100, '\n');
    cout << "Enter a string: ";
    getline(cin, str1);

when i ran First code Output :

Enter a string: hai
Enter another string: hello

Second code Output :

Enter another string: hello
Enter a string:

I can't input anymore, it just directly returned 0

Is it because of delimiters?

wohlstad
  • 12,661
  • 10
  • 26
  • 39

2 Answers2

2

std::istream::get leaves the newline character in the stream so if you use std::getline afterwards, it'll directly read that newline character.

You can get rid of it like so:

std::cin.get(str, 100, '\n');
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
std::getline(std::cin, str1);

Demo

But, it's easier if you don't mix std::getline and std::istream::get.

Ted Lyngmo
  • 93,841
  • 5
  • 60
  • 108
1

As you can see in the documentation for std::istream::get:

The delimiting character is not extracted from the input sequence if found, and remains there as the next character to be extracted from the stream (see getline for an alternative that does discard the delimiting character).

I.e. the difference is that std::getline disacrds the newline delimiter character. If you use std::istream::get it stays in the stream buffer, and when you try to extract the 2nd string you will get it into your variable.

Regarding your specific example, it's a better to use either std::getline or std::istream::get consistently, rather than mixing them up.
If you have a good reason to mix them, see how to in @TedLyngmo's answer.

wohlstad
  • 12,661
  • 10
  • 26
  • 39