-2

I started to get really good at programming but then I reached a part in this course that I always hate: Arrays. I never completely understood arrays in C++ and it's very confusing to me. I have a very simple program and I just need a little bit of help on what I'm doing wrong.

Here is my code so far:

#include <stdio.h>
#include <stdlib.h>

main() {

    int num[50];
    int i;

        for (i = 0; i < 50; i++) {
            printf("Enter a number (-999 to quit)\n ");
            scanf("%i", &num[i]);
            if (num == -999) {
                printf("you chose to quit\n ");
            }
        }
        printf("The numbers you entered are %i \n", num);
        system("pause");
    }

My questions are:

Why isn't -999 working properly? In a previous program I just used while (num != -999) and it worked great but it doesn't seem to be working in this case either. Why isn't the array printed out properly?

Please let me know what I'm doing wrong.

Swordfish
  • 12,971
  • 3
  • 21
  • 43
  • you read it in - but `num` is an array. – Daniel A. White Nov 24 '18 at 03:19
  • 2
    *How to fill an array with integers?* – with [`std::fill()`](https://en.cppreference.com/w/cpp/algorithm/fill), [`std::iota()`](https://en.cppreference.com/w/cpp/algorithm/iota) or [`std::generate()`](https://en.cppreference.com/w/cpp/algorithm/generate). – Swordfish Nov 24 '18 at 03:21
  • 2
    The reason it's not working properly is because you are ignoring honking warning messages from your compiler. No self-respecting C++ compiler will compile the shown code and stay absolutely quiet. Do not ignore warnings and alert messages from your compiler, even though it agreed, reluctantly, to finish compiling your code. Your compiler is always barking at you for a reason, telling you that you're doing something horribly wrong. Listen to your compiler. Your compiler is your friend. Experienced C++ developers turn on extra compiler warnings, so it barks even if it smells anything funny. – Sam Varshavchik Nov 24 '18 at 03:22
  • 2
    Are you compiling this code really as C++, or rather as C? No C++ compiler should accept this code. –  Nov 24 '18 at 03:23
  • @DanielA.White So should I change it for i instead? – Micheal Hunter Nov 24 '18 at 03:23
  • No, what you should do is think about what you told your computer to do: you asked your computer to test if the address of the `num` array is whatever "-999" means for a memory address. That's obviously not what you want. Remember: a computer always does what you tell it to do, instead of what you want it to do. Tell your computer what it should do instead of comparing the address of the `num` array with the funny memory address "-999". – Sam Varshavchik Nov 24 '18 at 03:26
  • 1
    @eukaryota I'm using C++ – Micheal Hunter Nov 24 '18 at 03:27
  • @MichealHunter Which compiler? – Swordfish Nov 24 '18 at 03:27
  • @SamVarshavchik I'm using visual studio and I think the compiler is great but I'm not experienced and I don't understand the error messages from it. Can you give me a hint with code on what I need in order for the program to stop at -999? – Micheal Hunter Nov 24 '18 at 03:30
  • *Why isn't -999 working properly?* Search term: break – user4581301 Nov 24 '18 at 03:31
  • I already gave you a hint: you need to tell your computer exactly what you want it to do, instead of comparing the memory address of the `num` array to memory address -999, which is what you told the computer to do. – Sam Varshavchik Nov 24 '18 at 03:31
  • -999 is not working because you stored it in num[i] and you are looking for it in num. Should be `if (num[i] == -999) {` – Gardener Nov 24 '18 at 03:34
  • In addition to what's already been suggested: Turn on warnings. Good things will come out! – Ted Lyngmo Nov 24 '18 at 03:34
  • 2
    Compiler error: Syntax is invalid and cannot be transformed into a program. Compiler warning: Syntax is valid and can be transformed into a program, but that program probably doesn't do what you expect. Compiler warnings are your first line of defense against logic errors. Turn them on and turn them up **LOUD!** – user4581301 Nov 24 '18 at 03:37
  • @MichealHunter Visual C++ 2017 does not compile it, see the error messages and warning in the bottom right-hand box: https://godbolt.org/z/gZMp_3 If you are _really_ sure that you are compiling it set to C++, I would like to know the Visual Studio version. I think both errors given by the 2017 version should have always been errors, but I don't know Visual C++ well. –  Nov 24 '18 at 03:39
  • 2
    I just realized your edit: Your file is named `.c`, so I am pretty sure you are compiling it as C, not C++. Are you intending to write C++ or C? Verify your compiler settings. The two languages do not work the same way although they have a lot of overlap in syntax in semantics. –  Nov 24 '18 at 03:44
  • *.c is a C source file, **not C++**. However even though the file name is *.c, MSVC is a C++ compiler and its C support is *very *bad. in C++ `std::array` and `std::vector` would be much easier to use. POD array is also nothing complex, just a linear storage of values, but you need to learn a small rule of array decaying to pointer – phuclv Nov 24 '18 at 03:58
  • @phuclv I've never used Visual Studio. If the file is named `.c` it will still compile it as C though, right? –  Nov 24 '18 at 04:08
  • 1
    @eukaryota yes, but you might face many issues [Why doesn't C code compile properly in Visual Studio?](https://stackoverflow.com/q/21037917/995714), [What issues can I expect compiling C code with a C++ compiler?](https://stackoverflow.com/q/861517/995714) – phuclv Nov 24 '18 at 04:14
  • @eukaryota With standard settings yes. – Swordfish Nov 24 '18 at 04:24
  • @MichealHunter Rename your file to `something.cpp` and enjoy the error messages. – Swordfish Nov 24 '18 at 04:26

3 Answers3

1
if (num == -999)

This compares the base address of num to the value -999, which is interpreted to be an address. Not the intended behavior. Check against num[i] not num.

printf("The numbers you entered are %i \n", num);

The %i specifier is used for a single int, but num is an array of them. Change to:

printf("The numbers you entered are:\n");
for (int i = 0; i < n; ++i) {
    if (num[i] == -999)
        break;
    printf("%i\n", num[i]);
}

where n is the number of elements in num (which may be less than 50).

A suggestion: since this is C++ code, it's a good idea to use cout and C++ libraries instead of printf and C libraries.

lost_in_the_source
  • 10,998
  • 9
  • 46
  • 75
  • Thanks for your help. Everyone has been yelling at me and saying this is C and not C++ but this is how I coded all my previous assignments and it made sense to me, I never learned "cout" in my course and I don't understand what break; is for? – Micheal Hunter Nov 24 '18 at 03:43
  • @MichealHunter breaks out of the for loop and continues the code beyond it – lost_in_the_source Nov 24 '18 at 03:44
  • @MichealHunter By all modern standards, that IS C code compiled with a very forgiving C++-compiler. – Swordfish Nov 24 '18 at 03:47
  • @MichealHunter I am sorry if it seemed like yelling. This was not intended. However everything is pointing to the fact that you are actually learning and using C, not C++. So in your own interest you should know that. It will save you lots of confusion in the future. If that was wrong and a C++ compiler actually accepted your code I would also just like to know about it out of pure interest. –  Nov 24 '18 at 03:50
  • @eukaryota No need to apologize, I understand why you guys are disturbed by this but I am confused as well. This is an online class and the instructor in the videos sometimes says "in c" and sometimes he says "in c++" and that really annoyed me too since the beginning of this semester. I'm just glad I only have 3 more weeks to go to deal with all his confusion. – Micheal Hunter Nov 24 '18 at 04:00
  • 2
    @MichealHunter Sounds like a terrible course then. In any case if the files are named `.c`, the identifier `std` never appears and all system header includes end in `.h` then you are probably writing C, not C++. And if your functions don't have a return type (`main()`) then you are learning very outdated C. Good luck. –  Nov 24 '18 at 04:05
1

Since you still claim (or are being told) that what you have written is C++, here an example of what it would look like in C++:

#include <iostream>
#include <vector>
#include <iterator>
#include <algorithm>

int main()
{
    std::cout << "Gimme Numbers! Just enter something thats not a number to end.\n";
    std::vector<int> numbers{ std::istream_iterator<int>{ std::cin },
                              std::istream_iterator<int>{} };

    std::cout << "\nYa << " << numbers.size() << " Numbas:\n";
    std::copy(std::begin(numbers), std::end(numbers),
              std::ostream_iterator<int>{ std::cout, "\n" });
}

Sample Output:

Gimme Numbers! Just enter something thats not a number to end.
15
45
97
8545
4654
5454
4564
54654
end

Ya 8 Numbas:
15
45
97
8545
4654
5454
4564
54654

Now the same with persons instead of int. Notice how main() is unchanged short of the strings for output and the type person instead of int:

#include <iostream>
#include <vector>
#include <iterator>
#include <algorithm>
#include <string>

struct person {
    std::string name;
    int age;
};

std::istream& operator>>(std::istream &is, person &p)
{
    std::string name;
    if (!(is >> name) || name == ".") {
        is.setstate(std::ios::failbit);
        return is;
    }
    int age;
    if (is >> age)
        p = { name, age };
    return is;
}

std::ostream& operator<<(std::ostream &os, person const &p)
{
    return os << p.name << ", age " << p.age;
}

int main()
{
    std::cout << "Gimme names and their ages! End with \".\"\n";
    std::vector<person> persons{ std::istream_iterator<person>{ std::cin },
                                 std::istream_iterator<person>{} };

    std::cout << "\nYa " << persons.size() << " buddies:\n";
    std::copy(std::begin(persons), std::end(persons),
              std::ostream_iterator<person>{ std::cout, "\n" });
}

Sample Output:

Gimme names and their ages! End with "."
Monica 45
Carl 35
Lydia 23
Alex 89
.

Ya 4 buddies:
Monica, age 45
Carl, age 35
Lydia, age 23
Alex, age 89
Swordfish
  • 12,971
  • 3
  • 21
  • 43
  • I'm not claiming that buddy, my online professor is. This is an online class and the instructor in the videos sometimes says "in c" and sometimes he says "in c++" and that really annoyed me too. I believe you. – Micheal Hunter Nov 24 '18 at 05:19
  • @MichealHunter *I'm not claiming that buddy* – thaty why I wrote "or are being told". I just hope you see the pure beauty of C++ now compared to C ;) – Swordfish Nov 24 '18 at 05:22
  • To me it looks like C++ is a lot more complicated with all the "<<" and the "::" – Micheal Hunter Nov 24 '18 at 05:43
  • @MichealHunter That would certainly change fast if you'd try to get the hang of it. What looks easier for reading an integer `int foo; scanf(" %d", &foo);` or `int foo; std::cin >> foo;` ? – Swordfish Nov 24 '18 at 05:52
0

To make this work, you have to provide a break statement to exit your for loop.

You also need to read the number into a slot of the array, and then check the slot, not the entire array, to see if the new slot holds the -999

#include <stdio.h>
#include <stdlib.h>

int main()
{

    int num[50];
    int i;

    for (i = 0; i < 50; i++) {
        printf("Enter a number (-999 to quit)\n ");
        // Scan the input into an integer slot in your array
        scanf("%i", &num[i]);

        // Check the slot to see if you an exit condition
        if (num[i] == -999) {
            printf("you chose to quit\n ");
            break;  // you have to exit the for loop by 
            // issuing a 'break;' after you get the -999

        }
    }

    int numbers_read = i;

    // print out the array -- Loop through all of the numbers
    // using a for loop and an index, up to the number that were read in:
    printf("The numbers you entered are: \n");
    for(int j= 0; j < numbers_read; j++) {
        printf("%i \n", num[j]);

    }


    system("pause");
}
Gardener
  • 2,591
  • 1
  • 13
  • 22
  • Thank you so much for your help. This is the best way to help because now in the future I will know that I need to use a break if I had the same issue. – Micheal Hunter Nov 24 '18 at 04:02