简体   繁体   中英

Display an array of 'double' numbers with unknown size in c++

Update 1: I need help with this the second part of this. I am asking the user to input numbers and to stop by using a zero. But then I want to display that code back. This is how far I got because when I want to display it it gives me different numbers. I'm ignoring user errors assuming when they input the first time it will be correct. But I do want them to input negative numbers.

#include <iostream>
#include <iomanip>
using namespace std;

int main ()
{
    float data;
    int count=0;
    int*arr=new int[count];

    //get amount of numbers inputted 
    cout<<"Please enter floating point data.\n";
    cout<<"After the last number has been entered press 0 (zero) \n";
    cin>>data;
    for (; data != 0 ; ++count)
    {
        cin>>data;
    }
    cout<<count<<endl;
    cout<<endl;
    //display back data
    cout<<"The numbers enterd are: "<<endl; 
    for(int i=0; i<count; i++)
    {
        cout<<arr[i]<<endl;
    }

    cout<<endl;

system ("pause");
return 0;
}

**Update 2:**This code is part of a bigger project I'm working on. My professor is never going to see the code he just cares that it is working. The design of my code is not a priority in this case. Also I have never used std::vector before so I needed another way to do it. But this is what I did and it worked fine. I also commented off delete []arr because my code wouldn't run properly if I didn't do that.

#include <iostream>
#include <iomanip>
using namespace std;

int main ()
{ 

    double data; 
    int count=0; 
    double *arr =new double[count]; 

    //get data 
    cout<<"Please enter floating point data."<<endl; 
    cout<<"After the last number has been entered press 0 (zero)"<<endl; 
    do
    {
        cin>>arr[count]; 
        data = arr[count]; 

        count++; 

    }while(data != 0); 

    //display back data 
    cout<<"The numbers entered are: "<<endl; 
    for(int i=0; i<(count-1); i++) 
    { 
        cout<<arr[i]<<endl;
    } 


    //delete []arr;  

 system ("pause");
 return 0;
 }

The given example code,

#include <iostream>
#include <iomanip>
using namespace std;

int main ()
{
    float data;
    int count=0;
    int*arr=new int[count];

    //get amount of numbers inputted 
    cout<<"Please enter floating point data.\n";
    cout<<"After the last number has been entered press 0 (zero) \n";
    cin>>data;
    for (; data != 0 ; ++count)
    {
        cin>>data;
    }
    cout<<count<<endl;
    cout<<endl;
    //display back data
    cout<<"The numbers enterd are: "<<endl; 
    for(int i=0; i<count; i++)
    {
        cout<<arr[i]<<endl;
    }

    cout<<endl;

system ("pause");
return 0;
}

… has many issues:

  • Coding: using float for no reason.
    The default floating point type in C and C++ is double . Eg the literal 3.14 is of type double , and any float value is promoted to double when passed to variadic C function. Only use float where a requirement is imposed by the context, eg a C API, or storing a zillion values in limited memory.

  • Coding: using a raw array and a new -expression.
    The task is trivial when using std::vector . It's not a good idea to reinvent the wheel again and again. An exercise that requires you to reinvent std::vector or its most basic features should be very clear about that aspect: this isn't, so presumably reinvention is not required or what it's about.

  • Design: signalling end-of-input via special value.
    That value can't be inputted.

  • Coding: an input loop that doesn't store the numbers.
    Each number is stored in the same variable as the previous number, erasing the previous number. Store the numbers in a std::vector . Eg you can use the push_back method.

  • Coding: inconsistent convention for newline on output.
    Either use endl , or "\\n" , as default. Don't mix them randomly. Consistency is very important because someone reading the code, who assumes a competent programmer, must treat every departure from the established defaults as being due to some reason . When there is no reason this wastes time and effort.

  • Tool usage: the system( "pause" ) is silly, counter-productive & non-portable.
    In Visual Studio, which it appears you're using, just run the program via Ctrl + F5 . Or place a breakpoint on the last right brace of main , and run the program in the debugger via F5 .

  • Coding: the return 0; is superfluous.
    main is the only function that has a default return value. It has that in both C and C++. The default, 0 for success, is there to be used.


Example code with the above points, plus some, fixed.

This code is for C++11 or later so it won't compile directly with Visual C++ 2010 .

I leave it as an exercise for you to translate it to C++03, which is what your current compiler can handle. Do consider upgrading. It's a free tool.

#include <iostream>
#include <iomanip>              // std::setw
#include <string>               // std::(string, stod)
#include <vector>               // std::vector
using namespace std;

using Half_float = float;                       // Most often a silly choice.
using Float = double;                           // Default in C++.
using Extended_float = long double;             // Same as double in Visual C++.

auto read_line()
    -> string
{ string line; getline( cin, line ); return line; }

auto main() -> int
{
    cout << "Please enter floating point numbers like " << 3.15 << ", one per line.\n";
    cout << "After the last number just press return again (i.e. a blank line).\n";

    vector<Float> numbers;
    for( ;; )
    {
        cout << "#" << numbers.size() + 1 << "? ";
        string const line = read_line();
        if( line.empty() )
        {
            break;
        }
        numbers.push_back( stod( line ) );      // Here you CAN do input validation.
    }

    cout << numbers.size() << " numbers entered.\n";
    cout << "\n";

    cout << "The numbers entered were: \n";
    for( int i = 0; i < int( numbers.size() ); ++i )
    {
        cout << setw( 3 ) << i << ": " << numbers[i] << "\n";
    }
}
  • The code will access out-of-bounds of arr , which has zero elements, unless you enter 0 for the first prompt.
  • You didn't assign what you read to "elements or arr " (actually there will be no elements in arr ) at all.
  • There will be no reason why you should use array of int to store float data.

You should use std::vector , which works as variable-size array.

#include <iostream>
#include <iomanip>
#include <vector>
using namespace std;

int main ()
{
    float data;
    int count=0;
    vector<float> arr;

    //get amount of numbers inputted 
    cout<<"Please enter floating point data.\n";
    cout<<"After the last number has been entered press 0 (zero) \n";
    while(cin >> data && data != 0)
    {
        arr.push_back(data);
    }
    count = arr.size();
    cout<<count<<endl;
    cout<<endl;
    //display back data
    cout<<"The numbers enterd are: "<<endl; 
    for(int i=0; i<count; i++)
    {
        cout<<arr[i]<<endl;
    }

    cout<<endl;

    return 0;
}

If you have C++ 11 or above, use auto

replace

for(int i=0; i<count; i++)
{
    cout<<arr[i]<<endl;
}

with

for(auto v: arr){
    cout << v << endl;
}

Please remember, you'll need compiler supporting C++11 to use auto.

If C++ < 11, Use std::for_each

#include <iostream>
#include <iomanip>
#include <vector>
using namespace std;

void print(float v){
    cout << v << endl;
}


int main ()
{
    float data;
    int count=0;
    std::vector<float> arr;

    //get amount of numbers inputted
    cout<<"Please enter floating point data.\n";
    cout<<"After the last number has been entered press 0 (zero) \n";

    while(cin>> data && data != 0)
    {
        arr.push_back(data);
        ++count;
    }
    cout<<count<<endl;
    cout<<endl;

    //display back data
    cout<<"The numbers enterd are: "<<endl;
    std:for_each(arr.begin(), arr.end(), print);
    cout<<endl;

    system ("pause");
    return 0;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM