Thread: A loop and char problem

  1. #1
    Registered User
    Join Date
    Oct 2006
    Location
    UK/Norway
    Posts
    485

    A loop and char problem

    Hi.

    I am currently learning c++, by reading and doing exersises if find online.
    The exersis askes me to create a program that find the mean of 1,2,3 or 4 numbers.

    I know this can be done easily by writing one "small program" for each of the situations, but I want to try to make it a bit more advance.

    I want to use a char array where the numbers are seperated like this 1,2,3,7 and so one.

    But I have a few questions, how can I make sure the input given is a number? I was thinking of converting it to ancii, but it has to be a better way?
    And if I use a loop to assign the value from the char array to an int array, how can I do so that every whole number is placed at the same space? So that no[1] = 12, insted of no[1] = 1 and no[2] = 2

    here is my code so far:
    Code:
    #include <cstdlib>
    #include <iostream>
    
    using namespace std;
    
    int main()
    {
         
         char numbers[100];
         int no[100];
         
        //This will give the info about the program and how to use it
        cout <<"This program will to two things:\n";
        cout <<" - Find the average\n";
        cout <<" - Find the standar diviation\n\n";
        cout <<"How to use:\n";
        cout <<"Enter the values you would like to use for this exsample,\n";
        cout <<"please seperate them with a blank space " ":\n";
        
        //store the info in a variable for later use
         cin.getline ( numbers, 100, '\n' ); 
       
         //loop through the string and exstract the number
         //store it in a new variable
         for (int i = 0; i < 100; i++)
             {
             if (numbers[i] == ",")
                {
                //It is a seperator, nothing happesns
                //The loop just continius
                }
             else
                 {
                 no[i] = numbers[i];
                 }
                  
             }
        
        
        cout <<"\n\n\n";
        system("PAUSE");
        return 0;
    
    }
    EDIT:
    Why is the line "if (numbers[i] == ",")" not valid?

    thanks in advance
    Last edited by h3ro; 10-18-2006 at 11:14 AM.

  2. #2
    erstwhile
    Join Date
    Jan 2002
    Posts
    2,227
    numbers[i] is a single char, "," is a NULL-terminated string - you probably meant to use ','.

    You could use isdigit on each charcter in turn to determine if it's a number or not.
    CProgramming FAQ
    Caution: this person may be a carrier of the misinformation virus.

  3. #3
    Registered User
    Join Date
    Jan 2005
    Posts
    7,366
    >> how can I make sure the input given is a number?
    cin will figure out if the input is a number for you. It does follow its own rules on what is a number, so it won't allow commas. But if you are ok with following cin's rules for what is a number then just use that. The simplest way is to use a loop that continues until a valid number is input:
    Code:
    while (!(cin >> integerVariable))
    {
      cin.clear();
      cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); // Or simply cin.ignore(1000, '\n')
      // re-prompt.
    }
    You should include <limits> for numeric_limits and <ios> for streamsize. You can also just use a large number which should work fine in almost all cases. If you want to check for letters after the number it is a simple addition to the while control.

  4. #4
    The C eater *munch*
    Join Date
    Oct 2006
    Posts
    101
    you might find this interesting, tho i'm using int
    Code:
    #include <iostream>
    
    using namespace std;
    
    int main() {
       int i;
     
       while(cin >> i) {
          cout << i << "\n";
       }
    
       return 0;
    }
    the program above will ask the user input until the user gets bored ... you can terminate it by pressing EOF character which usually is CTRL + D ...

    hint : each time user put something, process the input in the while loop

  5. #5
    Registered User
    Join Date
    Jan 2005
    Posts
    7,366
    >> you can terminate it by pressing EOF character
    You can also terminate that loop by entering anything that is not a valid integer, so any non whitespace character would work.

  6. #6
    Registered User
    Join Date
    Oct 2006
    Location
    UK/Norway
    Posts
    485
    thanks for the quick replies

    Code:
         int x[10];
      for (int i = 0; i<10; i++)
      { while(cin >> x[i]) 
       {
          cout << x << "\n";
       }
    I have to put i in a loop right? I dont get this to work.

    Also, if I want to use my char methode, how can I check is nothing is enterd in one of the slots?

    this is what i have now, that works. but it acts weird if i enter less than 100 characters
    Code:
    #include <cstdlib>
    #include <iostream>
     #include <ctype.h>
    
    using namespace std;
    int isdigit (int c);
    
    int main()
    {
         
         char numbers[100];
         int no[100];
         int isNumber;
         
        //This will give the info about the program and how to use it
        cout <<"This program will to two things:\n";
        cout <<" - Find the average\n";
        cout <<" - Find the standar diviation\n\n";
        cout <<"How to use:\n";
        cout <<"Enter the values you would like to use for this exsample,\n";
        cout <<"please seperate them with a blank space " ":\n";
    
        
        //store the info in a variable for later use
         cin.getline ( numbers, 100, '\n' ); 
       
         //loop through the string and exstract the number
         //store it in a new variable
         for (int i = 0; i < 100; i++)
             {
             if (numbers[i] == ',')
                {
                //It is a seperator, nothing happesns
                //The loop just continius
                cout <<"its a thing\n";
                }
             else
                 {
                 isNumber = isdigit(numbers[i]);
                 if (isNumber != 0)
                    {
                    //no[i] = numbers[i];
                    cout <<"its a numner\n";
                    }
                 else
                     {
                     cout <<"its not a number\n";
                     }
                 }
                  
             }
        
    
        
        cout <<"\n\n\n";
        system("PAUSE");
        return 0;
    
    }
    Last edited by h3ro; 10-18-2006 at 11:59 AM.

  7. #7
    The C eater *munch*
    Join Date
    Oct 2006
    Posts
    101
    Quote Originally Posted by Daved
    >> you can terminate it by pressing EOF character
    You can also terminate that loop by entering anything that is not a valid integer, so any non whitespace character would work.
    ah ic... sorry, was my first C++ program.. been using C

  8. #8
    The C eater *munch*
    Join Date
    Oct 2006
    Posts
    101
    Code:
         int x[10];
      for (int i = 0; i<10; i++)
      { while(cin >> x[i]) // no need to loop, just a single cin 
       { // not neccessary
          cout << x << "\n";
       } // not neccessary

  9. #9
    Registered User
    Join Date
    Oct 2006
    Location
    UK/Norway
    Posts
    485
    Code:
    #include <cstdlib>
    #include <iostream>
     #include <ctype.h>
    
    using namespace std;
    int isdigit (int c);
    
    int main()
    {
         
         char numbers[100];
         int no[100];
         int isNumber;
         
        //This will give the info about the program and how to use it
        cout <<"This program will to two things:\n";
        cout <<" - Find the average\n";
        cout <<" - Find the standar diviation\n\n";
        cout <<"How to use:\n";
        cout <<"Enter the values you would like to use for this exsample,\n";
        cout <<"please seperate them with a , sign:\n";
    
        
        //store the info in a variable for later use
         cin.getline ( numbers, 100, '\n' ); 
       
         //loop through the string and exstract the number
         //store it in a new variable
         for (int i = 0; i < 100; i++)
             {
             if (numbers[i] == ',')
                {
                //It is a seperator, nothing happesns
                //The loop just continius
                cout <<"The character is = ','\n";
                }
             else if (numbers[i] == ' ')
                  {
                  //End the loop
                  i = 100;
                  cout <<"The character is = ' '\n";
                  }
             else
                 {
                 isNumber = isdigit(numbers[i]);
                 if (isNumber != 0)
                    {
                    //no[i] = numbers[i];
                    cout <<"The character is = 'Number'\n";
                    }
                 else
                     {
                     cout <<"The character is = 'Not Number'\n";
                     }
                 }
                  
             }
        
      
        cout <<"\n\n\n";
        system("PAUSE");
        return 0;
    
    }
    Feeling like I am starting to get somewhere now, kind of happy

    Only thing left for this program is to find out as I mentioned befor how to get the info from characters[i] to no[i].
    example:
    12 would use 2 slots in the array. I want each number to be in one array.

    Going to look into the other way of getting inputs later. Looks good
    thanks

  10. #10
    Registered User
    Join Date
    Jan 2005
    Posts
    7,366
    >> Only thing left for this program is to find out as I mentioned befor how to get the info from characters[i] to no[i].

    That's not going to be a simple task. For each number you are going to have to keep track of how many good digits have been added. That way you know where to put the next digit you find. Placing each digit in an int array doesn't really make sense, because you can't make a number out of the digits each separately in an array. You could put the characters that are digits into a character array, and then convert that string to an int with atoi. You could also do the conversion yourself. Each new digit means the previous value needs to bemultiplied by 10 and then the new digit added to it. You'll have to do that process for each number the user enters.

  11. #11
    Registered User
    Join Date
    Oct 2006
    Location
    UK/Norway
    Posts
    485
    Ok, I see.

    Than i might be better of trying to do it like posted before here:
    Code:
    #include <iostream>
    
    using namespace std;
    
    int main() {
       int i;
     
       while(cin >> i) {
          cout << i << "\n";
       }
    
       return 0;
    }
    But im am not sure of how to use it in my case. Could someone please explain it?

  12. #12
    Registered User
    Join Date
    Jan 2005
    Posts
    7,366
    I think the loops you tried before, with the while loop inside the for loop, could work. The difference is that you should use my version of the while loop, which handles non-numeric input, rather than yxunomei's example which just stops if the user types in anything that is not right.

    However, looking at your original program, it is possible that you don't want to handle bad input, you just want to stop if they enter anything other than a number (otherwise how would you know when they are done giving you numbers). In that case you would just need to modify yxunomei's example to have two variables, one for the index in the number array and one for the value input from the user. Then each time you get a value from the user you insert it into the array at that index and increment the index.

  13. #13
    Registered User
    Join Date
    Oct 2006
    Location
    UK/Norway
    Posts
    485
    Code:
    #include <iostream>
    
    using namespace std;
    
    int main() {
        int noOfArray = 100;
        int integerVariable[noOfArray];
        
        for (int i = 0; i < noOfArray; i++)
        {
            while (!(cin >> integerVariable[i]))
            {
              cin.clear();
              cin.ignore(numeric_limits<streamsize>::max(), '\n');
              cout << "Please enter a valid int!\n";
            }
        }
        
        
        cout <<"\n\n\nYou entered:\n";
        for (int i = 0; i < noOfArray; i++)
        {
            cout << integerVariable[i] <<"\n";
        }    
        
        
        system("pause");
        return 0;
    }
    Well, I got that to work, but the problem is that now I have to enter 100 numbers or what ever I sett it to. But how can I make this a bit more dynamic? So that the user can decide when he wants to stop typing.

    Aslo, is there a way to quarry the size of an array?

    Or should I just aks the user for how many numbers he would like to use, than finish the program and move on?

    Code:
    #include <iostream>
    
    using namespace std;
    float averageNo(int integerVariable[],int noOfArray);
    
    
    int main() {
        int noOfArray;
        
        cout << "How many numbers would you like to use for this program?\n";
        cin >> noOfArray;
        
        int integerVariable[noOfArray];
        
        
        cout << "\n\nEnter you numbers:\n";
        for (int i = 0; i < noOfArray; i++)
        {
            while (!(cin >> integerVariable[i]))
            {
              cin.clear();
              cin.ignore(numeric_limits<streamsize>::max(), '\n');
              cout << "Please enter a valid int!\n";
            }
        }
        //Not working
        cout << averageNo(integerVariable[noOfArray],noOfArray);
        
        
        
        
        system("pause");
        return 0;
    }
    
    int averageNo(int integerVariable[],int noOfArray)
    {
          
             cout <<"\n\n\nYou entered:\n";
        for (int i = 0; i < noOfArray; i++)
        {
            cout << integerVariable[i] <<"\n";
        } 
        char a = 's';
        return a;
    }
    Last edited by h3ro; 10-18-2006 at 04:19 PM.

  14. #14
    Registered User
    Join Date
    Jan 2005
    Posts
    7,366
    >> the problem is that now I have to enter 100 numbers or what ever I sett it to.
    Right, that's what I was talking about in my second paragraph.

    One solution is to ask before hand how many they want to enter as you did. Technically, int integerVariable[noOfArray]; is illegal in C++, but it might work on your compiler because it is allowed in C. You could just make that a large number (like 100 or 1000 or whatever you think the max should be) to be "safe". The best solution in C++ would be to use a vector which is allowed any reasonable size.

  15. #15
    Registered User
    Join Date
    Oct 2006
    Location
    UK/Norway
    Posts
    485
    Thanks to all of you that have helped me so far, I think im am starting to get a bit of a better grasp of it.

    I am alsmost finished now, but I get an error for this script:
    Code:
    #include <iostream>
    
    using namespace std;
    
    double averageFunc(int integerVariable[], int noOfArray);
    
    int main() {
        int noOfArray;
        int integerVariable[noOfArray];
        int allNumbers = 0;
        double average = 0;
        
        cout << "How many numbers would you like to use for this program?\n";
        cin >> noOfArray;
        
        
        cout << "\n\nEnter you numbers:\n";
        for (int i = 0; i < noOfArray; i++)
        {
            while (!(cin >> integerVariable[i]))
            {
              cin.clear();
              cin.ignore(numeric_limits<streamsize>::max(), '\n');
              cout << "Please enter a valid int!\n";
            }
        }
        
        average = (averageFunc(int integerVariable[i], int noOfArray));
        
        cout << "\n\nThe average of the " <<noOfArray;
        cout << " intigers you inputed are: " << average;
        cout << "\n\n";
        
        
        system("pause");
        return 0;
    }
    
    double averageFunc(int integerVariable[], int noOfArray)
    {
           for (int i = 0; i < noOfArray; i++)
        {
            allNumbers = allNumbers + integerVariable[i];
            average = allNumbers / noOfArray;   
        }
        
        return average;
    }
    There is something wrong with this line:
    Code:
    average = (averageFunc(int integerVariable[i], int noOfArray));
    but I cant really understand why and what to fix it to

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Can't get loop to work or validation
    By eminem3150 in forum C++ Programming
    Replies: 11
    Last Post: 01-15-2008, 06:21 AM
  2. Personal Program that is making me go wtf?
    By Submeg in forum C Programming
    Replies: 20
    Last Post: 06-27-2006, 12:13 AM
  3. Replies: 3
    Last Post: 03-04-2005, 02:46 PM
  4. simulate Grep command in Unix using C
    By laxmi in forum C Programming
    Replies: 6
    Last Post: 05-10-2002, 04:10 PM
  5. How do you search & sort an array?
    By sketchit in forum C Programming
    Replies: 30
    Last Post: 11-03-2001, 05:26 PM