0

Here's my problem. I have to read a line from the console, for example:

Name,Area,Cost

Then using the comma as the delimiter character, it has to name, area and cost and place them into their corresponding variable to be placed in a hash table. Then using a loop the program needs to continuously do this until the user types the exit statement to exit the loop. Which it adds to the variables just fine, but when I type exit, it just waits for what I assume is the delimiter character. But even then it doesn't exit.

Here's the whole code so far:

while (true) {

        getline(cin, name, ',');
        if (name == "exit") {
            break;
        }
        getline(cin, area, ',');
        cin >> cost;
        
        //code to see if the variables are placed
        cout << "results" << endl;
        cout << name << endl;
        cout << area << endl;
        cout << cost << endl;
        
}
    //code to check for exit
cout << "Loop has exited" << endl;

Mason Jar
  • 13
  • 3

1 Answers1

2

By default, std::getline() reads until '\n' (Enter) or EOF (Ctrl-Z on Windows, Ctrl-D on *Nix, etc) is encountered. If you specify a delimiter other than '\n', it will not stop reading on '\n' anymore. So, getline(cin, name, ','); will not stop reading when the user types in exit and presses Enter, it will stop only when the user types in a ',' character (or Ctrl-Z/Ctrl-D).

You should first use std::getline() with its default '\n' delimiter to read the user's entire input into a std::string until Enter is typed, then check if that string is "exit", and if not then you can use a std::istringstream to parse the string as needed, eg:

#include <string>
#include <sstream>

std::string line, name, area;
double cost;

while (std::getline(std::cin, line) && (line != "exit"))
{
    std::istringstream iss(line);
    std::getline(iss, name, ',');
    std::getline(iss, area, ',');
    iss >> cost;
        
    //code to see if the variables are placed
    std::cout << "results" << std::endl;
    std::cout << name << std::endl;
    std::cout << area << std::endl;
    std::cout << cost << std::endl;

    //add to heap command
}

//code to check for exit
std::cout << "Loop has exited" << std::endl;
Remy Lebeau
  • 505,946
  • 29
  • 409
  • 696
  • Ooooohhh. Read the whole line and THEN parse it. My next stop was just using char arrays and like a million loops, so Thank you! – Mason Jar Oct 06 '20 at 21:00