-4

I'm trying to figure out why when I read my string using getline() function my string gets empty

#include <bits/stdc++.h>
using namespace std; 
int main() {
    int n; 
    cin >> n; 
    string s;
    cin >> s;
    getline(cin,s);
    cout << s; 
     
    }
Fabbiucciello
  • 1,456
  • 2
  • 2
  • 9
  • That question is better. However, the answer is the same as in my comment to your previous question. That's just `getline` is defined. (See [here](https://en.cppreference.com/w/cpp/string/basic_string/getline)) – churill Mar 05 '21 at 16:09
  • 3
    please include a [mcve] along with input, output and expected output in the question – 463035818_is_not_a_number Mar 05 '21 at 16:09
  • 3
    why do you put the line `getline(cin,s)` ? You already did read the user input into `s` in the line above and then this: https://stackoverflow.com/questions/21567291/why-does-stdgetline-skip-input-after-a-formatted-extraction – 463035818_is_not_a_number Mar 05 '21 at 16:11
  • That's becuase I would like to read a string including spaces – Fabbiucciello Mar 05 '21 at 16:12
  • 1
    then you should remove `std::cin >> s` and read the answers here: https://stackoverflow.com/questions/21567291/why-does-stdgetline-skip-input-after-a-formatted-extraction. – 463035818_is_not_a_number Mar 05 '21 at 16:13
  • Can you please keep only one of `cin >> s` or `getline(cin,s)` (it won't fix the issue, but we will be able to at least reason about your program). – rustyx Mar 05 '21 at 16:25

1 Answers1

0

The getline reads characters from an input stream and places them into a string.

If you use "cin >> s" and then use getline(cin, s), you should first call cin.ignore() before it.

Because "std::getline()" performs the following:

  1. Calls s.erase()
  2. Extracts characters from input and appends them to s
  3. If no characters were extracted for whatever reason, getline sets failbit and returns.

You should modify your code like below:

string s;
cin >> s;
cin.ignore();
std::getline(std::cin, s);