Im new to dynamic arrays. What im trying to do
is get a line of number that are stored as charachters , but implement a dynamic array to store the charachters so the size of the number(i.e. number of digits) is unkown. After i convert the charachters to an integer, i want to add it to another line of charachters stored as dyanmic arrays.

What i need is an outline, or some helpful code so I can see
how dynamic arrays work.

Recommended Answers

All 8 Replies

char* str;
vector<int> ints; // dynamic array of ints
while (cin >> str) ints.push_back(atoi(str)); // adding

>vector<int> ints; // dynamic array of ints
No, it's a vector of int. I very much doubt that's what the OP was thinking of when saying "dynamic array". :icon_rolleyes:

>char* str;
>while (cin >> str) ints.push_back(atoi(str)); // adding

Really? Shall we explore the fact that this is probably the most classic of classic errors and anyone claiming to teach C++ should recognize it on sight? Where does str point? I'll let the gets-like bug slide because most C++ers don't see the connection, but you should also recognize atoi as a bug and avoid it like the plague.

Hi.I was really wondering:).How do you convert a string into an int without using atoi()? If you don't mind telling me.I would appreciate it.And i'm really sorry about what i've said back then.If it mathers ..

nobody gonna bother to give a tip on dynamic arrays for this pjct?

>How do you convert a string into an int without using atoi()?
In C I would say use strtol:

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

int main(void)
{
    char buf[BUFSIZ];

    printf("Enter a number: ");
    fflush(stdout);

    if (fgets(buf, sizeof buf, stdin) != NULL)
    {
        char *end;
        int x;

        errno = 0;
        x = (int)strtol(buf, &end, 0);

        if (errno != 0 || (*end != '\n' && *end != '\0'))
        {
            perror("Invalid input");
        }
        else
        {
            printf("Value\tSquared\tCubed\n");
            printf("%d\t%d\t%d\n", x, x * x, x * x * x);
        }
    }

    return 0;
}

In C++ I would say use some variant of Boost::lexical_cast or do it yourself with stringstream:

#include <iostream>
#include <sstream>
#include <string>

int main()
{
    using namespace std;

    string buf;

    cout<<"Enter a number: ";

    if (getline(cin, buf))
    {
        istringstream in(buf);
        int x;

        if (!(in>> x) || !in.eof())
        {
            cerr<<"Invalid input\n";
        }
        else
        {
            cout<<"Value\tSquared\tCubed\n";
            cout<< x <<'\t'<< x * x <<'\t'<< x * x * x <<'\n';
        }
    }
}

The problem with atoi is that it doesn't handle errors well. If you don't invoke undefined behavior (an easy thing to do with atoi), you get the supremely unhelpful error return value of 0. Ultimately, using atoi means pre-validating the string before calling atoi, which is silly since both of the two methods above do the same thing natively.

Oh, and for the record, this is how you safely read a C-style string using cin's >> operator:

if (cin>> setw(n - 1) >> str)
{
    // Successful input
}

It's important to realize that you don't have a pointer to infinite memory (especially if you fail to initialize the pointer). C-style strings don't grow automatically like std::string objects, and your code needs to take that into account.

>nobody gonna bother to give a tip on dynamic arrays for this pjct?
You haven't asked a sufficiently detailed question, which suggests you haven't tried to do it yourself before asking for "tips".

Thanks a lot Narue.

If I understood it right, then this is what you want:

//It won't work in MSVC(at least for me: at reading the string), but works in Code::Blocks
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
	char* read;
	cin >> read;
	int* line = new int[strlen(read)];
	for(int i=0; i<strlen(read); i++)
	{
		line[i] = atoi(read)/(int)pow((float)10, (float)strlen(read)-i-1);
		cout << line[i];
		read++;
	}
	return 0;
}

>It won't work in MSVC
And that didn't raise any red flags for you?

>char* read;
>cin >> read;

Pointers are not magic. If you try to write to an uninitialized pointer you don't get infinite memory, you get undefined behavior and access violations which tend to crash your program.

>int* line = new int[strlen(read)];
Um...I see a fundamental misunderstanding here. Most likely you're not familiar enough with the lower level aspects of C++ to give "tips" adequately. Also note that strlen is declared in <cstring>, which you failed to include.

>for(int i=0; i<strlen(read); i++)
I'm all for not optimizing prematurely, but things like calling strlen every iteration of a loop are best described as "premature pessimization". strlen (unless very cleverly written) walks across the length of the string looking for a null character. This is what your loop really looks like:

for (int i = 0; ; i++)
{
  size_t len = 0;

  while (read[len] != '\0')
  {
    ++len;
  }

  if (i >= len)
  {
    break;
  }
}

The for loop is walking over the length of the string, and strlen is walking over the length of the string. So the complexity of the loop, instead of the expected O(N), is really O(N^2). Pretty awful when you consider that correcting the error is trivial:

for (size_t i = 0, len = strlen(read); i < len; i++)

>line = atoi(read)/(int)pow((float)10, (float)strlen(read)-i-1);
That's about as close to concentrated evil as one can get without being intentionally malicious. ;)

commented: Thanks for giving this advices! +0
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.