在循环中读取输入,直到在C+&#x2B中达到哨兵值。

发布于 2025-01-24 02:45:28 字数 864 浏览 1 评论 0原文

我对C ++相对较新,我正在尝试编写一些要求用户输入数字并使用-999作为前哨值的代码来结束输入循环。他们输入的数字必须填充以后在二进制树中使用的数组。我遇到的问题是,如果输入-999,循环不会终止,我也不知道如何在不指定数组的大小的情况下将这些值读取到数组中。该程序必须根据给出多少输入来动态大小数组。我附上了代码。任何帮助将不胜感激!

#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;
    }

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;
    }

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

你在看孤独的风景 2025-01-31 02:45:28

这是一个可以执行您想要的程序。

#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

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

高冷爸爸 2025-01-31 02:45:28

除了所有其他问题之外,主要问题是:

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

您正在从标准输入中读取数组数字的第i-the元素。您将i与999进行比较,这基本上没有意义。为什么要比较i?为什么将其与999(而不是-999)进行比较?

让我们尝试修复它。从一个空的无限循环开始:

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

读一个整数:

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

现在让我们检查一下我们是否设法阅读了某些内容,如果不让我们退出循环。

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

如果我们阅读了-999,我们还需要从循环中退出:

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

现在您想将其放在数字的第三位置,所以:

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

好的,现在我们有一个工作循环(希望如此)。您的代码中还有哪些其他问题?

  1. int数字[] = {};
  2. j&lt; = sizeof(数字)

您无法在没有C ++的编译时间大小的情况下定义数组。使用std :: vector&lt;&gt;
然后,sizeof运算符不做您认为做的事情。将其保存为(很多?)。使用std :: vector :: size()。但是对于初学者来说,您可以假设1000个数字对每个人都足够(Bill Gates Docet),并将计数保留在变量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

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);
    }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文