Search code examples
c++getlinecin

Use of cin and getline for strings


I was recently doing a problem in C++:

Write a program to work out if a series of 5 digits are consecutive numbers. To make this easier, assumes the digits are a string:

string numbers = "10-9-8-7-6";

Make sure your code works for the following sequence, as well:

string numbers = "1-2-3-4-5";

I solved it, however I saw when I used cin for the string the console window threw some exception & didn't execute the program but on replacing it with getline, it worked perfectly.

Could anyone explain me the reason behind it because logically both should work properly.

The program is:

#include<iostream>
#include<string>

using namespace std;

void change(int x, int y, int &inc, int &dec)
{
    if (x - y == 1)
        ++dec;
    else if (y - x == 1)
        ++inc;
}

int main()

{
    string s = "", snum = "";
    cout << "enter 5 nos and use \'-\' to separate them: ";
    cin >> s;
    int i = 0, x = 0, y = 0, inc = 0, dec = 0;
    for (char &ch : s)
    {
        if (ch == '-')
        {
            ++i;
            if (i == 1)
            {
                y = stoi(snum);
                cout << y << endl;
            }
            else
            {
                x = y;
                y = stoi(snum);
                cout << x << " " << y << endl;
                change(x, y, inc, dec);
            }
            snum = "";
        }
        else
            snum += ch;
    }
    x = y;
    y = stoi(snum);
    cout << x << " " << y << endl;
    change(x, y, inc, dec);
    if (inc == 4 || dec == 4)
        cout << "ORDERED";
    else
        cout << "UNORDERED";
    return 0;

}

Solution

  • If you have to enter everything at the same time such as:

    10 9 8 7 6

    All on one line then cin does not record all that at the same time. Concerning cin it only takes the characters before a space (" ") for example. Getline however takes that entire line and uses it. Another way to do the same thing would be to use the cstdio library and have it set up with either using printf or puts to prompt, and then use gets to gather all the information from the puts prompt. This is what I assume why it works.

    Example:

    cstdio library

    char string[50];
    printf("Enter a string of text");
    gets(string);
    cout << string << endl;
    

    *EDIT

    After the comment below I realized what you are asking, and if you are assuming the numbers are strings, and they are separated with hyphens and no spaces then it should work fine. It shouldn't be the problem of cin by maybe something else?

    If there are spaces involved in your code then what I wrote above EDIT will be a simple solution to THAT problem.