Good afternoon guys,
I created a zero-argument constructor for structure Section and initialized number to 0 and name to an empty string. I created this so if the user decides to hit enter the program would terminate and the values would be initialize to the values of the constructor. The program does not exit when I hit enter. Can someone please help me out determining the problem and giving me a small explanation how this zero initialization works ? Thank you in advance .
#include <iostream>
using namespace std;
#include <string>
struct Section
{
int number;
string name;
Section()
{
number = 0;
name = "";
you are correct it does terminate using your code, but I actually want to terminate it when it
prompts for a section number and the user decides to hit enter instead of entering a section number. I try the below code but it gives me an error message "expression must have a class type"
for (int i = 0; i < n; i++)
{
cout << "Enter section number: ";
cin >> t->sections[i].number;
if (strlen(t-> sections.number[0] == '\0'))
{
return;
}
Looks like there is a mix up with name and number. The number variable is an integer so it doesn't make sense using strlen or array indices.
The name variables have type std::string so the easiest way to check if they're empty is to use the empty() member function. if (t.sections[i].name.empty())
Note that, unlike getline, the >> operator will not return if the user press enter without inputting anything. It will just continue waiting for more input. If you really want to allow the user to abort the input process by pressing enter while asked to input a number you probably should read the number as a string instead and then convert it to an integer using std::istringstream or std::stoi.
Please remove the empty code block from your first post. A bug in this forum prevents Firefox users from posting in this topic because of it.