0

The getline(cin, s1) function is not prompting me to input a string. it appears as if it is being skipped over even when the if condition is being met. any help? code is below. the problem is in the first if statement.

//Exercise 3.2

#include "stdafx.h"
#include <iostream>
#include <string>

using std::cin;
using std::cout;
using std::endl;
using std::string;

int main(){
char a1;

 cout << "Read line (L) or word (W)?:";
cin >> a1;

if (a1 == 'l'){
    string s1;
    getline(cin, s1);
    cout << s1 << endl;
}
else{
    string s1;
    while (cin >> s1){
        cout << s1 << endl;
    }
}
system("pause");
 return 0;   
}
Matt
  • 69
  • 1
  • 1
  • 7

1 Answers1

0

When you do:

cin >> some_char_variable;

it reads the char and leaves the input stream pointer pointing at the next character, which is invariably the newline you entered.

If you then do a getline(), it will get the line, which is delineated by that newline in the input stream that you left there.

This is the same problem as when you mix getchar() and fgets() in C, the combination of which generally always confuses newcomers.

I tend to avoid mixing the two styles, such as by using getline() everywhere, such as with:

string choice;
getline(cin, choice);

if (choice[0] == 'l') ...

But, if you must mix them, you can clear out the line before trying to accept more data, with something like:

cin.ignore(numeric_limits<streamsize>::max(), '\n');
paxdiablo
  • 772,407
  • 210
  • 1,477
  • 1,841
  • so what would be the correct way to code the IF statement in order to properly get prompted by the input stream? – Matt Nov 05 '14 at 02:30