Overclock.net › Forums › Software, Programming and Coding › Coding and Programming › getline(cin,string) and loops
New Posts  All Forums:Forum Nav:

getline(cin,string) and loops

post #1 of 14
Thread Starter 
I've been stressing over this one for a while.
This is my first semester with C++ so I am not all that acquainted with the subtleties of the language.

Anyways, I'm trying to create a function that asks for the Name of a City and will compare that string to an array of strings(In this case city names) and if none match, the loop will ask for another string.

My issue is that the getline(cin,string) line keeps getting skipped over and the loop goes through once with the fail message setting off. I have tried many versions of this loop with boolean functions and sending the string to a different function. I am stumped by this.

please be kind! I'm still learning! biggrin.gif
post #2 of 14
Quote:
Originally Posted by PRloaded;13559122 
I've been stressing over this one for a while.
This is my first semester with C++ so I am not all that acquainted with the subtleties of the language.

Anyways, I'm trying to create a function that asks for the Name of a City and will compare that string to an array of strings(In this case city names) and if none match, the loop will ask for another string.

My issue is that the getline(cin,string) line keeps getting skipped over and the loop goes through once with the fail message setting off. I have tried many versions of this loop with boolean functions and sending the string to a different function. I am stumped by this.

please be kind! I'm still learning! biggrin.gif

Post the code. Also in your testing, do you use a city with two words?
Valery
(13 items)
 
  
CPUMotherboardGraphicsRAM
i5 2500k GA-P67A-UD4-B3 Radeon 7970 Reference G. Skill Sniper 
Hard DriveOptical DriveOSMonitor
Corsair NOVA SSD 64gb + 500gb Storage + 1TB Storag HP DVD burner Windows 7 64bit 37" 1080p60hz 
KeyboardPowerCaseMouse
Razer Blackwidow Ultimate Rosewill Lightning 1000W Single Rail LianLi PC-K58 Razer Spectre 
Mouse Pad
Razer Goliathus Speed 
  hide details  
Reply
Valery
(13 items)
 
  
CPUMotherboardGraphicsRAM
i5 2500k GA-P67A-UD4-B3 Radeon 7970 Reference G. Skill Sniper 
Hard DriveOptical DriveOSMonitor
Corsair NOVA SSD 64gb + 500gb Storage + 1TB Storag HP DVD burner Windows 7 64bit 37" 1080p60hz 
KeyboardPowerCaseMouse
Razer Blackwidow Ultimate Rosewill Lightning 1000W Single Rail LianLi PC-K58 Razer Spectre 
Mouse Pad
Razer Goliathus Speed 
  hide details  
Reply
post #3 of 14
Yeah, post code and we can help. smile.gif
Project 4
(13 items)
 
  
CPUMotherboardGraphicsRAM
i5 750 Lynnfield @ 4.4 GHz, 1.41v EVGA P55 SLi (132-LF-E655-KR) - A72 BIOS EVGA GeForce GTX 680 4GB G.Skill Ripjaws @ 9-9-9-24, 1.51V 
Hard DriveOptical DriveOSMonitor
80GB Intel X25-M SSD + 500GB WD + 2TB Samsung F3 Samsung Super Writemaster DVD+-R Windows 7 Ultimate Edition Samsung SyncMaster 2433 24" 
KeyboardPowerCaseMouse
Logitech G15 Corsair TX750 750W Corsair Obsidian 800D + Scythe Kaze Master Ace Razer Deathadder Respawn - Black 
Mouse Pad
Steelseries QcK Medium - Black 
  hide details  
Reply
Project 4
(13 items)
 
  
CPUMotherboardGraphicsRAM
i5 750 Lynnfield @ 4.4 GHz, 1.41v EVGA P55 SLi (132-LF-E655-KR) - A72 BIOS EVGA GeForce GTX 680 4GB G.Skill Ripjaws @ 9-9-9-24, 1.51V 
Hard DriveOptical DriveOSMonitor
80GB Intel X25-M SSD + 500GB WD + 2TB Samsung F3 Samsung Super Writemaster DVD+-R Windows 7 Ultimate Edition Samsung SyncMaster 2433 24" 
KeyboardPowerCaseMouse
Logitech G15 Corsair TX750 750W Corsair Obsidian 800D + Scythe Kaze Master Ace Razer Deathadder Respawn - Black 
Mouse Pad
Steelseries QcK Medium - Black 
  hide details  
Reply
post #4 of 14
Thread Starter 
Quote:
Originally Posted by donkru;13560273 
Post the code. Also in your testing, do you use a city with two words?

yeah. other wise i'd use cin by itself. its weird, it works fine with cin(One word).
I had to turn in my code for my class so I modified it with ints *which worked*.
I have a final in about 2 hours so I'll type the code up the best I can remember it.
post #5 of 14
try this, use cin.ignore to flush the buffer before input.
Code:
char city[100];
int count = 0;

cin.ignore();   //flushes the buffer
cin.getline(city, 100);   //can hold up to 100 chars

while(count == 0){
for(int i = 0; i < # of cities to compare; ++i){

      if(strcmp(city, cityarray[i]) == 0){
                  cout << city << "is a match" << endl; 
                  count = 1;
                  break;      
      }                  

}
cin.ignore();
cin.getline(city, 100);
}

Edited by surfbumb - 5/19/11 at 12:02pm
Black Silence
(15 items)
 
  
CPUMotherboardRAMHard Drive
i5 3570k @ 4.5 GHz Asus P8Z77-M Pro Kingston HyperX Genesis 8 GB - 1600 MHz Seagate Barracuda 250 GB 
Optical DriveCoolingOSMonitor
Samsung WriteMaster Noctua NH-D14 Windows 10 ASUS VS24AH-P 
KeyboardPowerCaseMouse
Logitech Navigator Enermax Infiniti 650W Fractal R3 Black Pearl Razer Death Adder 
Mouse PadAudio
SteelSeries QcK Mass Altec Lansing FX4021 
  hide details  
Reply
Black Silence
(15 items)
 
  
CPUMotherboardRAMHard Drive
i5 3570k @ 4.5 GHz Asus P8Z77-M Pro Kingston HyperX Genesis 8 GB - 1600 MHz Seagate Barracuda 250 GB 
Optical DriveCoolingOSMonitor
Samsung WriteMaster Noctua NH-D14 Windows 10 ASUS VS24AH-P 
KeyboardPowerCaseMouse
Logitech Navigator Enermax Infiniti 650W Fractal R3 Black Pearl Razer Death Adder 
Mouse PadAudio
SteelSeries QcK Mass Altec Lansing FX4021 
  hide details  
Reply
post #6 of 14
Thread Starter 
I get an error when I try to compile it.

ine 83 "no matching function for call to `strcmp(char[100], std::string&)' "
Code:
#include <cstdlib>
#include <iostream>
#include <math.h>
#include <iomanip>
#include <string>
#include <limits>
#include <fstream>
#include <string.h>
#include <stdio.h>

using namespace std;

//this will eventually be filled with the info listed below
//later to be called when displaying the final ticket info
struct completeticketInfo{
       string ticketName;
       string ticketDeparture;
       string ticketDestination;
       string ticketGate;
       string ticketFlightNum;
       int    ticketDepartureMonth;
       int    ticketDepartureDay;
       int    ticketDepartureHour;
};
       
//This gets the departure time info
class flightDeparture{
      public: 
              int monthGet(){
                  int monthSet;
                  cout <<"Enter Month of Departure from 1-12: ";
                  
                  
                  while (!(cin >> monthSet) || monthSet < 1 || monthSet > 12){
                        cin.clear();
                        cin.ignore( std::numeric_limits<std::streamsize>::max(), '\n' );
                        cout << "Please Enter a Correct Input from 1-12: ";
                  }
                  return monthSet;
              }
              int dayGet(){
                  int daySet;
                  cout <<"Enter Day of Departure from 1-31: ";
                  
                  
                  while (!(cin >> daySet) || daySet < 1 || daySet > 31){
                        cout << "Please Enter a Correct Input from 1-31: ";
                        cin.clear();
                        cin.ignore( std::numeric_limits<std::streamsize>::max(), '\n' );
                  }
                  return daySet;
              }                                                 

};
              
//gets the destination             
class flightDestination{
      
      public:
             char destinationGet(){
                   int count = 0;
                   char citySet[100];
                   
                   string destinations[10] = {
                          "New York",
                          "Los Angeles",
                          "Mexico City",
                          "London",
                          "Shanghai",
                          "New Dehli",
                          "Madrid",
                          "Paris",
                          "Lisbon",
                          "Brisbane",
                          };
      
                   cout << "Please Enter in Your Destination City of Choice: ";
                   cin.ignore();
                   cin.getline(citySet,100);
                   while (count == 0){
                         for (int i = 0; i < 10; ++i){
                             if(strcmp(citySet, destinations[i]) == 0){
                                cout << citySet<< "is a match" << endl; 
                                count = 1;
                                break; 
                                }
                         }
                          cout <<"Try Again: ";
                          cin.ignore();
                          cin.getline(citySet,100);
                   }
      }
                       
             //display the selection of destinations                                  
             void displayAll(string destination[]){
                  int n;
                  cout <<"  Destinations Available"<<endl<<endl;
                  for (n=0 ; n < 10; n++){
                      cout <<setw(3)<<n+1<<"."<<setw(21)<<destination[n]<<endl;
                  }
                  cout <<"\n";
             }     
}; 
                  
int main(int argc, char *argv[]){
   
   char destinationChoice[100];
   string PassengerName;
   string DepartureName;
   string getText;
   int    departM;
   int    departD;
   cout << "Welcome to Poor Richards Airlines!"<<endl;
   cout << "Our services are currently unavailable but will resume shortly"<<endl;
   cout << "In the meantime, please feel free to choose your next destintination"<<endl;
   cout <<"and we will be sure to make reservations for our next flight.\nThank You!\n\n\n";
   
   string destination[10] = {
          "New York-US",
          "Los Angeles-US",
          "Mexico City-MEX",
          "London-UK",
          "Shanghai-CHN",
          "New Dehli-IND",
          "Madrid-SPN",
          "Paris-FRN",
          "Lisbon-PORT",
          "Brisbane-AUS"};
   
   cout << "Enter Passenger Info\n\n\n";
   cout << "Name: ";
   getline (cin,PassengerName);
   cout << "Departure City: ";
   getline (cin,DepartureName);
   
   //object for flightDeparture
   flightDeparture departureInfo;
   departM = departureInfo.monthGet();
   departD = departureInfo.dayGet();
   
   cout<<endl<<endl;
   //object for flightDestination
   flightDestination flightInfo;
   flightInfo.displayAll(destination);
   


   destinationChoice = flightInfo.destinationGet();
   
   ifstream openfile ("flights.txt");
   if (openfile.is_open()){
      while(!openfile.eof())
      {
       getline (openfile,getText);
       cout << getText <<endl;
       }
      }
   cout <<"Enter Flight You Wish To Reserve 1-6: ";
   
      
              
 
     
    system("PAUSE");
    return EXIT_SUCCESS;
}

post #7 of 14
Quote:
Originally Posted by PRloaded;13564980 
I get an error when I try to compile it.

line 83 "no matching function for call to `strcmp(char[100], std::string&)' "

I believe that was this line:

if ( strcmp (citySet, destinations) == 0 )

citySet is a string, and destinations
is a letter. You can't compare the two.

If you just want to know if the two are equal, just do

// If they're strings
if ( citySet == destinations )

// If they're chars
if ( strcmp (citySet, destinations) == 0 )

// If citySet is a char* and destination is a string
if ( strcmp (citySet, destinations.c_str()) == )
Foldatron
(17 items)
 
Mat
(10 items)
 
Work iMac
(9 items)
 
CPUMotherboardGraphicsGraphics
i7 950 EVGA x58 3-way SLI EVGA GTX 660ti GTX 275 
RAMHard DriveHard DriveHard Drive
3x2GB Corsair Dominator DDR3-1600 80GB Intel X25-M SSD 2TB WD Black 150GB WD Raptor 
Hard DriveOSMonitorKeyboard
2x 150GB WD V-raptor in RAID0 Win7 Home 64-bit OEM 55" LED 120hz 1080p Vizio MS Natural Ergonomic Keyboard 4000 
PowerCase
750W PC P&C Silencer CoolerMaster 690 
CPUGraphicsRAMHard Drive
Intel Core i5 2500S AMD 6770M 8GB (2x4GB) at 1333Mhz 1TB, 7200 rpm 
Optical DriveOSMonitorKeyboard
LG 8X Dual-Layer "SuperDrive" OS X Lion 27" iMac screen Mac wireless keyboard 
Mouse
Mac wireless mouse 
CPUGraphicsRAMHard Drive
i7-2600K AMD 6970M 1GB 16GB PC3-10600 DDR3 1TB 7200rpm 
Hard DriveOptical DriveOSMonitor
256GB SSD 8x DL "SuperDrive" OS X 10.7 Lion 27" 2560x1440 iMac display 
Monitor
27" Apple thunderbolt display 
  hide details  
Reply
Foldatron
(17 items)
 
Mat
(10 items)
 
Work iMac
(9 items)
 
CPUMotherboardGraphicsGraphics
i7 950 EVGA x58 3-way SLI EVGA GTX 660ti GTX 275 
RAMHard DriveHard DriveHard Drive
3x2GB Corsair Dominator DDR3-1600 80GB Intel X25-M SSD 2TB WD Black 150GB WD Raptor 
Hard DriveOSMonitorKeyboard
2x 150GB WD V-raptor in RAID0 Win7 Home 64-bit OEM 55" LED 120hz 1080p Vizio MS Natural Ergonomic Keyboard 4000 
PowerCase
750W PC P&C Silencer CoolerMaster 690 
CPUGraphicsRAMHard Drive
Intel Core i5 2500S AMD 6770M 8GB (2x4GB) at 1333Mhz 1TB, 7200 rpm 
Optical DriveOSMonitorKeyboard
LG 8X Dual-Layer "SuperDrive" OS X Lion 27" iMac screen Mac wireless keyboard 
Mouse
Mac wireless mouse 
CPUGraphicsRAMHard Drive
i7-2600K AMD 6970M 1GB 16GB PC3-10600 DDR3 1TB 7200rpm 
Hard DriveOptical DriveOSMonitor
256GB SSD 8x DL "SuperDrive" OS X 10.7 Lion 27" 2560x1440 iMac display 
Monitor
27" Apple thunderbolt display 
  hide details  
Reply
post #8 of 14
Quote:
Originally Posted by PRloaded;13564980 
I get an error when I try to compile it.

ine 83 "no matching function for call to `strcmp(char[100], std::string&)' "
Code:
#include <cstdlib>
#include <iostream>
#include <math.h>
#include <iomanip>
#include <string>
#include <limits>
#include <fstream>
#include <string.h>
#include <stdio.h>

using namespace std;

//this will eventually be filled with the info listed below
//later to be called when displaying the final ticket info
struct completeticketInfo{
       string ticketName;
       string ticketDeparture;
       string ticketDestination;
       string ticketGate;
       string ticketFlightNum;
       int    ticketDepartureMonth;
       int    ticketDepartureDay;
       int    ticketDepartureHour;
};
       
//This gets the departure time info
class flightDeparture{
      public: 
              int monthGet(){
                  int monthSet;
                  cout <<"Enter Month of Departure from 1-12: ";
                  
                  
                  while (!(cin >> monthSet) || monthSet < 1 || monthSet > 12){
                        cin.clear();
                        cin.ignore( std::numeric_limits<std::streamsize>::max(), '\n' );
                        cout << "Please Enter a Correct Input from 1-12: ";
                  }
                  return monthSet;
              }
              int dayGet(){
                  int daySet;
                  cout <<"Enter Day of Departure from 1-31: ";
                  
                  
                  while (!(cin >> daySet) || daySet < 1 || daySet > 31){
                        cout << "Please Enter a Correct Input from 1-31: ";
                        cin.clear();
                        cin.ignore( std::numeric_limits<std::streamsize>::max(), '\n' );
                  }
                  return daySet;
              }                                                 

};
              
//gets the destination             
class flightDestination{
      
      public:
             char destinationGet(){
                   int count = 0;
                   [B]string citySet;[/B]                   
                   string destinations[10] = {
                          "New York",
                          "Los Angeles",
                          "Mexico City",
                          "London",
                          "Shanghai",
                          "New Dehli",
                          "Madrid",
                          "Paris",
                          "Lisbon",
                          "Brisbane",
                          };
      
                   cout << "Please Enter in Your Destination City of Choice: ";
                   cin.ignore();
                   cin >> citySet;
                   while (count == 0){
                         for (int i = 0; i < 10; ++i){
                           [B]  if(strcmp(citySet.c_str(), destinations[i].c_str()) == 0){[/B]                                cout << citySet<< "is a match" << endl; 
                                count = 1;
                                break; 
                                }
                         }
                          cout <<"Try Again: ";
                          cin.ignore();
                          [B]cin >> citySet;[/B]                   }
      }
                       
             //display the selection of destinations                                  
             void displayAll(string destination[]){
                  int n;
                  cout <<"  Destinations Available"<<endl<<endl;
                  for (n=0 ; n < 10; n++){
                      cout <<setw(3)<<n+1<<"."<<setw(21)<<destination[n]<<endl;
                  }
                  cout <<"\n";
             }     
}; 
                  
int main(int argc, char *argv[]){
   
   char destinationChoice[100];
   string PassengerName;
   string DepartureName;
   string getText;
   int    departM;
   int    departD;
   cout << "Welcome to Poor Richards Airlines!"<<endl;
   cout << "Our services are currently unavailable but will resume shortly"<<endl;
   cout << "In the meantime, please feel free to choose your next destintination"<<endl;
   cout <<"and we will be sure to make reservations for our next flight.\nThank You!\n\n\n";
   
   string destination[10] = {
          "New York-US",
          "Los Angeles-US",
          "Mexico City-MEX",
          "London-UK",
          "Shanghai-CHN",
          "New Dehli-IND",
          "Madrid-SPN",
          "Paris-FRN",
          "Lisbon-PORT",
          "Brisbane-AUS"};
   
   cout << "Enter Passenger Info\n\n\n";
   cout << "Name: ";
   getline (cin,PassengerName);
   cout << "Departure City: ";
   getline (cin,DepartureName);
   
   //object for flightDeparture
   flightDeparture departureInfo;
   departM = departureInfo.monthGet();
   departD = departureInfo.dayGet();
   
   cout<<endl<<endl;
   //object for flightDestination
   flightDestination flightInfo;
   flightInfo.displayAll(destination);
   


   destinationChoice = flightInfo.destinationGet();
   
   ifstream openfile ("flights.txt");
   if (openfile.is_open()){
      while(!openfile.eof())
      {
       getline (openfile,getText);
       cout << getText <<endl;
       }
      }
   cout <<"Enter Flight You Wish To Reserve 1-6: ";
   
      
              
 
     
    system("PAUSE");
    return EXIT_SUCCESS;
}


changed in bold...convert the std::string to a c-string

I didn't know you were able to use all strings...so i changed the citySet to a std::string...looks cleaner too.

Also what school in SD do you attend? how do you like the program?
Edited by surfbumb - 5/19/11 at 3:30pm
Black Silence
(15 items)
 
  
CPUMotherboardRAMHard Drive
i5 3570k @ 4.5 GHz Asus P8Z77-M Pro Kingston HyperX Genesis 8 GB - 1600 MHz Seagate Barracuda 250 GB 
Optical DriveCoolingOSMonitor
Samsung WriteMaster Noctua NH-D14 Windows 10 ASUS VS24AH-P 
KeyboardPowerCaseMouse
Logitech Navigator Enermax Infiniti 650W Fractal R3 Black Pearl Razer Death Adder 
Mouse PadAudio
SteelSeries QcK Mass Altec Lansing FX4021 
  hide details  
Reply
Black Silence
(15 items)
 
  
CPUMotherboardRAMHard Drive
i5 3570k @ 4.5 GHz Asus P8Z77-M Pro Kingston HyperX Genesis 8 GB - 1600 MHz Seagate Barracuda 250 GB 
Optical DriveCoolingOSMonitor
Samsung WriteMaster Noctua NH-D14 Windows 10 ASUS VS24AH-P 
KeyboardPowerCaseMouse
Logitech Navigator Enermax Infiniti 650W Fractal R3 Black Pearl Razer Death Adder 
Mouse PadAudio
SteelSeries QcK Mass Altec Lansing FX4021 
  hide details  
Reply
post #9 of 14
Thread Starter 
Quote:
Originally Posted by surfbumb;13565903 
changed in bold...convert the std::string to a c-string

I didn't know you were able to use all strings...so i changed the citySet to a std::string...looks cleaner too.

Also what school in SD do you attend? how do you like the program?

I attended SDSU but I didn't like their engineering department so I'm currently at Southwestern so I can transfer next year to UCSC. This programming class is actually from San Diego City College and it's online so I can't really give my opinion on their program tongue.gif
Edited by PRloaded - 5/19/11 at 5:03pm
post #10 of 14
Thread Starter 
got it!
I guess the whole clearing the buffer was the issue.
I still don't fully understand alot of the subtle inner workings of C++ yet.

One question though, can structures be initialized by variables?

if you look at my code you can see I made a structure for the ticket info.
I plan to fill them up with named variables with data in them every tutorial that I see has it like
Code:
ticketInfo fillTicket = {
"New York"
11
15
6
......
}


does it have to be like this or can I do
Code:
ticketInfo fillTicket = {
PassengerName
DepartureName
DestinationChoice
........
}
New Posts  All Forums:Forum Nav:
  Return Home
  Back to Forum: Coding and Programming
Overclock.net › Forums › Software, Programming and Coding › Coding and Programming › getline(cin,string) and loops