Thread: Problems with array to string assignment.

  1. #1
    Registered User
    Join Date
    Mar 2004
    Posts
    220

    Problems with array to string assignment.

    Ok i'm new to the board so don't shoot me if i'm doing something wrong here....hehe...plz...I just have some problems with my code here. It's only 1 page or so. The only reason i'm posting all of it is so that you can see what i'm doing..kinda new to C++. The program is supposed to take any number of integers from the user and average them out with variable argument list usage in a function.

    So here it is:
    Code:
    1. #include <iostream>
        #include <stdlib.h>
        #include <stdio.h>
        #include <stdarg.h>
    5. using namespace std;
        int average2(int num2, ...);
        int average2(int num2, ...) {
        int sum = 0, count = 0, currentNum = num2; 
        va_list currentList;
    10.va_start(currentList, num2);
        while (currentNum != 0) {
            sum += currentNum;
            count++;
            currentNum = va_arg(currentList, int);
    15.   }
        va_end(currentList);
        int final = sum / count;
        return final;
    }
    20. int main() {
           cout << "How many entries do you want to average? \n> ";
           int i;
           cin >> i;
           int array[i + 1];
    25.  cout << "Enter in the values that you want to average. \n> ";
           int k = 0;
           char t;
           for (k == 0; k < i; k++) {
    30.  cin >> array[k];
           cout << "\nPress y to continue. \n";
           cin >> t;
           if (t == 'y') {
                    t = 'n';
    35.           break;
            }
            else
                    goto end;
        }
    40.array[i+1] = 0;
         char *original = array[];
         int len = strlen(original), doublelen = len * 2;
         char string[doublelen];
    45.   for (int p = 0; p < doublelen; p++) {
              for (int e = -1; e < doublelen; e++) {
                    string[e + 1] = original[e];
              }
            for (int x = 0; x < doublelen; x++) {
                    string[x + 1] = ",";
    50.     }
           }
           cout << average2(int(string[]));
           end:
           system("pause");
    54.  }

    Forgive me for my lack of commenting but I had to save space here..

    Not only am I not sure if this will actually fully compile, because i'm converting an int array to char array...and converting a char array to a string..and trying to put a string into an int based function..but i'm not sure what is wrong on line 41...

    I'm just making this program to get a more firm grasp on C++, it isn't supposed to fully compile, more along the lines of..bits and pieces are supposed to function correctly. Eventually i'll resolve this little string to int problem I have..

    So any idea's?

    And feel free to state something you don't like about my coding style or..how I code things or whatnot..what you see wrong with my looping etc. anything that you could reccomend that would make this better?

    -Thank you.
    OS: Windows XP Pro CE
    IDE: VS .NET 2002
    Preferred Language: C++.

  2. #2
    Disturbed Boy gustavosserra's Avatar
    Join Date
    Apr 2003
    Posts
    244
    Hi. First, if you post code, do not put that numbers at the left side. So one can copy your code and compile it without making any changes.
    First, you canŽt use a variable to alloc an array like you are doing, but use this:
    Code:
    int i=10;
    int array[i]; //wrong
    int* array = new int[i];
    Ok, now you must not use int and char mixed like you did, unless you have very specific motives.
    Second, a char is, for example 'a', not "a". This solves the problem of line 51.
    Third, you are using the function average wrong. Learn a little bit more. =)
    Nothing more to tell about me...
    Happy day =)

  3. #3
    Registered User
    Join Date
    Mar 2004
    Posts
    220
    Hmm...thx for the help

    But the only other question I have for now is....

    How would I put in integers into the average2() function that are in array[]?

    I'm having some trouble with this because I don't know how I would put in the comma's that seperate the arguments..

    And even if I do some sort of a string i'm not sure if the function would function correctly since it takes in int values..

    I was thinking along the lines of creating a string with for loops that will add together... 'array[0], array[1], array[2]' etc etc for however many numbers the user wants to average...but i'm not exactly sure how to do that..
    OS: Windows XP Pro CE
    IDE: VS .NET 2002
    Preferred Language: C++.

  4. #4
    Disturbed Boy gustavosserra's Avatar
    Join Date
    Apr 2003
    Posts
    244
    IŽll be honest, I never used va_list and such. For average I would use a function that receives an array, and the size of it.
    Code:
    double average(const int* numbers, const int q){
    	double totalSum = 0.0;
    	for(int i=0 ; i<q ; i++)
    		totalSum += numbers[i];
    	return totalSum/q;
    }
    Nothing more to tell about me...
    Happy day =)

  5. #5
    Registered User
    Join Date
    Mar 2004
    Posts
    220
    Thank you I'll remember that.

    Yea variable argument lists are C I beleive..doesn't surprise me.
    OS: Windows XP Pro CE
    IDE: VS .NET 2002
    Preferred Language: C++.

  6. #6
    Disturbed Boy gustavosserra's Avatar
    Join Date
    Apr 2003
    Posts
    244
    Ok! But as far as I know, C++ does not provide such thing. When programminc C++ me, and others that I know, use C to achieve differente things. Actually, everthing that is C, is C++ to me. But it is just an opinion. =)
    Nothing more to tell about me...
    Happy day =)

  7. #7
    Registered User
    Join Date
    Mar 2004
    Posts
    220
    Ahh yes I understand what you mean

    Since really you can use C with C++ and C++ was based off of C, I guess you could consider them the same =) Since there are structs and other sorts of things from C that are supported used in most books and make at least some mention of them. lol, I always find it funny....that something thats what....50 lines of code...can be summed up in 10...lol.
    OS: Windows XP Pro CE
    IDE: VS .NET 2002
    Preferred Language: C++.

  8. #8
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    Posts
    9,897
    >But as far as I know, C++ does not provide such thing.
    C++ supports variable length argument lists. However, the feature is so error prone that you won't see it often at all (except in the *printf and *scanf families).

    You're working thinking too hard. Try to keep your program simple and a solution will always present itself:
    Code:
    #include <iostream>
    #include <vector>
    
    using namespace std;
    
    int average ( vector<int> numbers )
    {
      int sum ( 0 );
    
      for ( vector<int>::iterator i = numbers.begin(); i != numbers.end(); i++ )
        sum += *i;
    
      return sum / numbers.size();
    }
    
    int main()
    {
      vector<int> numbers;
      int num;
    
      cout<<"Enter a list of numbers or Q to end (ex.  1 2 3 4 5 Q): ";
      while ( cin>>num )
        numbers.push_back ( num );
      cout<<"The average is "<< average ( numbers ) <<endl;
    }
    My best code is written with the delete key.

  9. #9
    Registered User
    Join Date
    Mar 2004
    Posts
    220
    Prelude, could you do me the most kindest favor and explain what your code is going through each line?

    /me is new..

    If you don't want to take the time I understand, but it would be a great help

    But even if you don't you've already helped alot =) Thank you.
    OS: Windows XP Pro CE
    IDE: VS .NET 2002
    Preferred Language: C++.

  10. #10
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    Posts
    9,897
    >#include <iostream>
    Replace the line with the contents of iostream so that we can use standard I/O.

    >#include <vector>
    Replace the line with the contents of vector so that we can use the standard vector class.

    >using namespace std;
    Simplify the syntax by making all standard names visible.

    >int average ( vector<int> numbers )
    The average function takes a vector of integers called numbers and returns the average in the form of an integer.

    >int sum ( 0 );
    Declare a variable called sum to hold the total of the numbers and initialize it with zero.

    >for ( vector<int>::iterator i = numbers.begin(); i != numbers.end(); i++ )
    Loop over every item in the vector (from the beginning to the end). I also could have used indices instead of iterators:
    Code:
    for ( int i = 0; i < numbers.size(); i++ )
    >sum += *i;
    *i means to return the value of the iterator. In this case that would be an integer, one of the numbers that the user enters. Add that to the sum.

    >return sum / numbers.size();
    Return the average. sum is the total and the size member function of numbers tells you how many numbers there are. A simple division gives you the average.

    >int main()
    Define a starting point for the program.

    >vector<int> numbers;
    Declare a vector of integers. It's like an array of integers, but better.

    >int num;
    Declare a variable to get user input.

    >cout<<"Enter a list of numbers or Q to end (ex. 1 2 3 4 5 Q): ";
    Prompt the user for input.

    >while ( cin>>num )
    Loop as long as the input you get is good. This takes advantage of cin going into a failure state if the input is not the expected type.

    >numbers.push_back ( num );
    Add the new input to the end of the vector.

    >cout<<"The average is "<< average ( numbers ) <<endl;
    Call average with the vector of user input and print the return value.
    My best code is written with the delete key.

  11. #11
    Registered User
    Join Date
    Mar 2004
    Posts
    220
    I have some more questions if that's allright with you....

    1)Why are Vectors better then arrays and what makes them different?

    2)What do you mean by simplifying the syntax by making the namespaces visible? Does it mean that if you just use that namespace that it will replace 'cout << "";' with 'std::cout<< "";' at compile time? Or does it mean something else?

    3)int sum ( 0 ); is equal to int sum = 0; yes?

    4)What do you mean by iterator in that for loop?

    5)What is .begin() and what header file does it lie in? I assume that it's equal to the first entry in a vector but I need clarification..never seen that before. And i've never seen Vectors in my life for that matter.

    6)Why are you using :: in that for loop?

    7)push_back() does what exactly? Yes it allows the user new input but..how does it do that? And what is it going through?

    8)So if your using cin with vectors...cin recognizes whitespace and allows you to assign...1 2 and 3 to three entries in the vector?

    -Thanks again, I appreciate it.
    OS: Windows XP Pro CE
    IDE: VS .NET 2002
    Preferred Language: C++.

  12. #12
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    Posts
    9,897
    >1)Why are Vectors better then arrays and what makes them different?
    They resize themselves, manage their own memory, and provide useful functions.

    >2)What do you mean by simplifying the syntax by making the namespaces visible?
    I mean you don't have to explicitly qualify everything in the standard library with std::.

    >3)int sum ( 0 ); is equal to int sum = 0; yes?
    Yes.

    >4)What do you mean by iterator in that for loop?
    Basically an object that acts like a pointer. If you don't know what that means, don't worry about it. A lot of experienced programmers are confused by iterators.

    >5)What is .begin() and what header file does it lie in?
    It's a member function of the vector class.

    >And i've never seen Vectors in my life for that matter.
    I should have used indices then.

    >6)Why are you using :: in that for loop?
    Because the vector class defines an iterator type within itself. To get to it I need to specify the scope of iterator. That scope is vector<int>, thus vector<int>::iterator is the qualified type.

    >7)push_back() does what exactly?
    It puts its argument on the end of the vector.

    >how does it do that? And what is it going through?
    It doesn't matter. The simplified code would be something like this though:
    Code:
    void vector :: push_back ( const T& x )
    {
      if ( block_n == block_alloc )
        resize();
      base[block_n++] = x;
    }
    >cin recognizes whitespace
    cin's >> operator is delimited by whitespace, yes. If you're input is "1 2 3 Q" then the loop will do what you want, but be in a failure state after the loop because Q was not convertable to int.
    My best code is written with the delete key.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. char Handling, probably typical newbie stuff
    By Neolyth in forum C Programming
    Replies: 16
    Last Post: 06-21-2009, 04:05 AM
  2. Pointer to array of string and Array of Pointer to String
    By vb.bajpai in forum C Programming
    Replies: 2
    Last Post: 06-15-2007, 06:04 AM
  3. String issues
    By The_professor in forum C++ Programming
    Replies: 7
    Last Post: 06-12-2007, 09:11 AM
  4. Unknown Memory Leak in Init() Function
    By CodeHacker in forum Windows Programming
    Replies: 3
    Last Post: 07-09-2004, 09:54 AM
  5. array problems
    By slamit93 in forum C++ Programming
    Replies: 7
    Last Post: 04-25-2002, 01:09 PM