Hi guys,

Looking at this I know it is straightforward, but that hasn't meant that I have been able to get the solution - so here I am! I am entering serial numbers into a set container which is of type string. I want to be able to enter serial numbers into the set until the user simply presses enter, meaning that "blank" stops input. For the code that I will show you, I have used "X" as the way the user stops input. Here is the code:

ItemizedProductLine::ItemizedProductLine(ProductCode pc, double rrp, double sp, int oh, char* desc): ProductLine(pc, rrp, sp, oh, desc){
    
    string serial = "0";

    while(serial.at(0) != 'X')
    {
        cout << "Please enter serial number:" << endl;
    
        cin >> serial;
        
        serialNumbers.insert(serial);
    }
}

As you can see, this does allow the user to stop entering data by pressing "X". However, I can see that this is a horrible way of doing it. Furthermore, it does not achieve my real goal of having the user simply press enter to stop input.

I should add that I am aware that using an array would make it very easy. However, I am limited by the fact that I am entering serial numbers as strings. Furthermore, I now really want to know how you do this using strings! Can anyone shed any light on this problem? Thanks in advance.

Daniel

using getline should work for you. I would suggest this

// inside function
string serial;
cout << "Please enter a serial number. Enter to quit: ";
getline(cin, serial);
while(!serial.empty())
{
    serialNumbers.insert(serial);
    cout << "Please enter a serial number. Enter to quit: ";
    getline(cin, serial);
}

It is to be noted there is no error checking here so the user could enter a letter and it would be excepted.

use getline() instead of >> operator and it will work

int main()
{

    string serial = "0";

    while(serial != "")
    {
        cout << "Please enter serial number:" << endl;
    
        getline(cin,serial);
        
    }
    cout << "All done\n";
}

[edit]Oops! didn't see Nathan's reply [/edit]

Edited 6 Years Ago by Ancient Dragon: n/a

In this case, using getline is appropriate:

ItemizedProductLine::ItemizedProductLine(ProductCode pc, double rrp, double sp, int oh, char* desc): ProductLine(pc, rrp, sp, oh, desc)
{
  for (;;)
  {
    cout << "Please enter serial number:" << endl;
    string serial;
    getline(cin,serial);
    if (serial.empty())break;
    serialNumbers.insert(serial);
  }
}

Thanks guys! Much appreciated. This site really is fantastic! Have a great day/night!

This question has already been answered. Start a new discussion instead.