1

So I was reading about getline(cin, string); and tried to use it to give a string with multiple word. My simple code:

#include <iostream>
#include <string>

int main()
{
    string test;
    getline(cin, test);
    cout << test << endl;

return 0;
}

This works perfectly

But if I use the same code in a little more complicated program, it just gets ignored!

My just-started program:

#include <iostream>
#include <fstream>
#include <limits>
#include <string>
using namespace std;

struct mainstruct
{
ofstream f_list;

void write()
{
    int rating;
    string name, watch, wprint;
    cout << "Modifying" << endl;
    f_list.open ("TextFile.txt", ios::app);
    cout << "Name/Title?" << endl;
    getline(cin, name);
    //cin.clear();
    //cin.ignore(numeric_limits<streamsize>::max(), '\n');
    cout << "Rating?" << endl;
    cin >> rating;
    //cin.clear();
    //cin.ignore(numeric_limits<streamsize>::max(), '\n');
    cout << "Watched or unwatched?" << endl;
    getline(cin, watch);
    //cin >> watch;
    if (watch == "w" || watch == "yes" || watch == "y")
    {
        watch = "W";
        wprint = "Watched";
    }
    else
    {
        watch = "DW";
        wprint = "Didn't watch";
    }
    cout << name << " (" << rating << "/10) (" << wprint << ") has been added to the list" << endl;
    f_list << name << " " << rating << " " << watch << endl;
    //cin.clear();
    //cin.ignore(numeric_limits<streamsize>::max(), '\n');
}

void read()
{
    cout << "Reading" << endl;
    f_list.open("TextFile.txt");
}

void shutdown()
{
    f_list.close();
}
};

int main()
{
string answ, test;
mainstruct o_list;
do
{
    cout << "\n\nWould you like to check the list, modify or close it?" << endl;
    cin >> answ;
    if (answ == "modify" || answ == "m" || answ == "write" || answ == "w")
    {
        o_list.write();
    }
    else if (answ == "check" || answ == "c" || answ == "read" || answ == "r")
    {
        o_list.read();
    }
    else if (answ != "modify" || answ != "m" || answ != "write" || answ != "w" || answ != "check" || answ != "c" || answ != "read" || answ != "r")
    {
        if (answ == "close" || answ == "quit" || answ == "q")
        {
            cout << "File closed, list saved" << endl;
        }
        else
        {
            cout << "Invalid input" << endl;
        }
    }
    o_list.shutdown();
} while (answ != "close" && answ != "quit" && answ != "q");
o_list.shutdown();

getline(cin, test);
cout << test << endl;

return 0;
}

Here my getlines just get ignored! (I used cin >> string; before thats why those cin.clear();'s and cin.ignore();'s are there.

0 Answers0