I have a program where I’m specifying the file to be read using cin, so I run the program ./prog < file.txt, but in the following code, cin doesn’t grab anything. Could someone explain why line is empty after the code executes?
void Building::build(){
char mode;
cin >> mode >> sizeFloors >> numFloors;
if(mode == 'M')
readMap(sizeFloors, numFloors);
}
^^ this executes fine
void Building::readMap(int floorSize, int numFloors){
string line;
int curFloor(numFloors - 1);
while( curFloor >= 0 ){
cin >> line;
if(line.empty()){
cout << "Error: input file too short" << endl;
exit(1);
}
}
^^ here line.empty() returns true
this is the input file
M
4
1
WWWW
WWWW
WWWW
WWWW
so clearly line shouldnt return empty
When mixing formatted input (i.e., using
operator>>()) and unformatted input (e.g.,std::getline()) you need to make sure that you are at a location you are interested in. The formatted input operators stop reading the moment their format is satisfied. For example, reading a character just reads that one character. Any following charactters, e.g., a newline, is left in the input.std::getline()stops reading at the first newline received. I guess, after you entered your menu selection you hit newline and this is wherestd::getline()stops (same if the menu selection is in a file on its own).A typical approach when switching between formatted and unformatted I/O is to skip all leading spaces:
Alternatively, you can ignore everything up to and including the first newline:
Which approach is used clearly depends on the content of your data. For example, if you want to read code where leading namespace matters skipping up to the first non-whitespace is not an award winning idea. However, in many situations using
std::wsworks just fine.