-1

I'm relatively new to C++ and I'm trying to write some code that asks a user to enter numbers and use -999 as a sentinel value to end the input loop. The numbers they enter must populate an array to be used in a binary tree later. The issue I'm having is the loop doesn't terminate if -999 is entered, and I also don't know how to read those values into the array without specifying how large the array is. The program must dynamically size the array based on how many inputs were given. I have attached my code. Any help is greatly appreciated!

#include <iostream>
#include <string.h>
//#include "binarySearchTree.h"
//#include "binaryTree.h"

using namespace std;
int i;
int n;

struct Node {
    int data;
    struct Node* left;
    struct Node* right;
}

Node(int val)
{
    data = val;
    left = NULL;
    right = NULL;
};

int main() {

    //struct Node* root = new Node(1);

    cout << "Enter values up to -999: \n";
    int numbers[] = {};

    for(int i =0; i!=999; i++){
        cin >> numbers[i];
    }

    cout << "\nYour numbers are: ";

    for(int j=0; j<=sizeof(numbers) ; j++){
        cout << numbers[j] << " ";
        }
    return 0;
    }
  • 5
    Where are you learning C++ from? There is a lot wrong with this code, I'm surprised you've gotten to the point you are entering numbers and running into the "not terminating when you enter -999" problem. (I did not downvote.) – Eljay Apr 25 '22 at 17:12
  • Largely self teaching. I have taken an online course though. I dont understand why this got down voted. I researched it heavily before posting this... I cant find plenty on terminating loops, but not when the array size has to be dynamic. – RobinInTheHood Apr 25 '22 at 17:15
  • 1
    Why would you use a dynamic array when it appears you're attempting to implement a doubly linked list? If you really want a dynamic array, use `std::vector`. – Fred Larson Apr 25 '22 at 17:17
  • 3
    I would recommend getting a [C++ book](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list). – n. m. could be an AI Apr 25 '22 at 17:20
  • I took a code boot camp and I'm just trying to do some projects to implement the concepts. I'm by no means well versed in C++... just looking for advice. I don't claim anything in this code to be the proper or best way to do anything. That's why I'm here. – RobinInTheHood Apr 25 '22 at 17:20
  • The code you have posted [does not compile](https://godbolt.org/z/Yo9GG3vzT). Perhaps start by fixing that. `-Wall -Werror -pedantic` are highly recommended (this is a polite way to spell "mandatory" BTW). – n. m. could be an AI Apr 25 '22 at 17:25
  • 1
    You're testing `i != 999`, but `i` is not the value you're reading from the user, `numbers[i]` is. – Nathan Pierson Apr 25 '22 at 17:25
  • The thing is, this code cannot compile or run to the point where you say it is failing. What we would like to see is a [mcve]. The problem you describe is likely to be because you are testing the array index against 999, not the input value against -999. – Fred Larson Apr 25 '22 at 17:26
  • C++ is probably the most complicated programming language in general use. You can't learn it from quicky courses and even university courses trend towards insufficient. It's just too wide a topic. Self-taught is pretty much the only way to go, but that self-teaching needs to be backstopped with good reference materials. Learn the fundamentals from a good book and then you probably have enough inoculation against stupidity to be able to safely use Internet tutorials. – user4581301 Apr 25 '22 at 18:25

2 Answers2

0

Here is a program that does what you want.

#include <iostream>
#include <vector>

// never, ever use using namespace std;

int main()
{
   std::vector<int> input; // this is the way to spell "an array that can grow as needed"
                           // int numbers[] = {}; is not one.

   int number;
   while (std::cin >> number // check whether the input is successful, i.e. a number 
                             // is entered. entering a non-number or an
                             // end-of-file indicator is a failure
          && number != -999) // and whether that number is not -999
   {
      input.push_back(number); // add it to the end of our growing-as-needed array
   }

   for (auto i : input) // that's how you enumerate entries in the array
   {
      std::cout << i << " ";
   }
   std::cout << "\n";   // print a newline when you are done

}

Live demo

n. m. could be an AI
  • 112,515
  • 14
  • 128
  • 243
  • Thank you, this is very insightful. I think this shows how low quality the c++ class I took was. They swore by namespace std and never explained what it was or why to use or not use it. We also never covered vectors. I'm going to have to look into them and learn how they work. – RobinInTheHood Apr 25 '22 at 17:53
  • Also, could you elaborate or provide documentation on the (auto i : input) ? I've never seen enumeration done that way. – RobinInTheHood Apr 25 '22 at 17:56
  • It's a [range-based for loop](https://en.cppreference.com/w/cpp/language/range-for). Essentially it means "for each element `i` that's contained in the range `input`, do the following..." – Nathan Pierson Apr 25 '22 at 18:03
0

Beside all other problems, the main problem is here:

for(int i =0; i!=999; i++){
    cin >> numbers[i];
}

You are reading from the standard input into the i-th element of the array numbers. You are comparing i with 999, which basically makes no sense. Why comparing i? And why comparing it with 999, instead of -999?

Let's try to fix it. Start with an empty infinite loop:

while (true) {
    // Read
    // Check
    // Use
}

Read an integer:

while (true) {
    // Read
    int val;
    cin >> val;
    // Check
    // Use
}

Now let's check if we managed to read something and if not let's exit from the loop.

while (true) {
    // Read
    int val;
    cin >> val;
    // Check
    if (cin.fail()) {
        break;
    }
    // Use
}

We need to exit from the loop also if we read a -999:

while (true) {
    // Read
    int val;
    cin >> val;
    // Check
    if (cin.fail()) {
        break;
    }
    if (val == -999) {
        break;
    }
    // Use
}

Now you want to put it in the i-th position of numbers, so:

int i = 0;
while (true) {
    // Read
    int val;
    cin >> val;
    // Check
    if (cin.fail()) {
        break;
    }
    if (val == -999) {
        break;
    }
    // Use
    numbers[i] = val;
    ++i;
}

Ok, now we have a working loop (hopefully). What other problems you have in your code?

  1. int numbers[] = {};
  2. j<=sizeof(numbers)

You cannot define arrays without a compile time size in C++. Use std::vector<>. Then, the sizeof operator doesn't do what you think it does. Save it for (much?) later. Use std::vector::size(). But for starters, you can assume that 1000 numbers will be enough for everyone (Bill Gates docet), and keep the count in variable i:

#include <iostream>
using namespace std;

int main() 
{
    cout << "Enter values. Use -999 to stop entering values.\n";
    int numbers[1000]; // We accept 1000 numbers at most 

    int i = 0;
    while (true) {
        // Read
        int val;
        cin >> val;
        // Check
        if (cin.fail()) {
            break;
        }
        if (val == -999) {
            break;
        }
        // Use
        numbers[i] = val;
        ++i;
    }

    cout << "Your numbers are: ";
    for (int j = 0; j < i; j++) {
        cout << numbers[j] << " ";
    }
    cout << '\n';

    return 0;
}

Switching to std::vector<> is much better. And learn Why is "using namespace std;" considered bad practice?:

#include <iostream>
#include <vector>

int main() 
{
    std::cout << "Enter values. Use -999 to stop entering values.\n";
    std::vector<int> numbers; 

    while (true) {
        // Read
        int val;
        std::cin >> val;
        // Check
        if (std::cin.fail()) {
            break;
        }
        if (val == -999) {
            break;
        }
        // Use
        numbers.push_back(val);
    }

    std::cout << "Your numbers are: ";
    for (int j = 0; j < numbers.size(); j++) {
        std::cout << numbers[j] << " ";
    }
    std::cout << '\n';

    return 0;
}

Finally, if you think that while(true) {} is ugly, you can use other versions of the same loop, e.g.:

    for (int val; std::cin >> val && val != -999;) {
        numbers.push_back(val);
    }
Costantino Grana
  • 3,132
  • 1
  • 15
  • 35
  • Thank you. This is very informative and really helps. The c++ course I took was accelerated and covered a new concept every 3 days. It was an awful crash course and I don't feel I learned much. This is showing me how many gaping holes are in my knowledge of the language. They never covered vectors and they always made us use namespace std for no reason. I'm going to have to learn more about vectors to full understand but this really helps. – RobinInTheHood Apr 25 '22 at 18:10
  • In any case remember to always accept the answer you like most and upvote the good answers (when you'll have the ability to do so). – Costantino Grana Apr 25 '22 at 19:09