Menu

Loop on String

2002-12-02
2012-09-26
  • Nobody/Anonymous

    I am trying to loop this program for a CS class of mine.  Everytime I try to do a do,while loop in the main part, it doesn't work. This isnt exactly a problem with Dev-C++, but i know there is someone here who can help.  Below is a copy of the program:

    #include <iostream.h>
    #include <stdlib.h>
    #include <string>
    //**********************************************************
    void WriteFirstLast(){

    string Name;
    cout << "Enter name in Last, First format: ";
    getline(cin, Name);
    cout << Name << endl;
    int comma = Name.find(",");
    string Last = Name.substr(0, comma);
    string First = Name.substr(comma + 2, 999);
    cout << First << " " << Last << endl;
    }
    //**********************************************************
    int main()
    {
    WriteFirstLast();
    system("PAUSE");
          return 0;
    }

     
    • Curtis Sutter

      Curtis Sutter - 2002-12-02

      // Start of Prog
      #include <iostream>
      #include <stdlib.h>
      #include <string>
      using namespace std;

      //**********************************************************
      bool WriteFirstLast()
      {
        string Name;
        cout << "Enter name in Last, First format: ";
        getline(cin, Name);
        if (Name == "") // CLS If nothing is entered
          return false; // CLS Quit loop
        cout << Name << endl;
        int comma = Name.find(",");
        string Last = Name.substr(0, comma);
        string First = Name.substr(comma + 2, 999);
        cout << First << " " << Last << endl;
        return true; // CLS Everything A-ok
      }
      //**********************************************************
      int main()
      {
        bool success = true;
        while(success) // CLS Loop condition based on return val of WriteFirstLast()
        {
          success = WriteFirstLast();
        }
        system("PAUSE");
        return 0;
      }
      // End of Prog

      By not entering anything and just hitting 'enter' the loop will exit.  I believe that this is what you were looking for.

      Curtis

       

Log in to post a comment.

Want the latest updates on software, tech news, and AI?
Get latest updates about software, tech news, and AI from SourceForge directly in your inbox once a month.