Thread: help about while loop

  1. #1
    Registered User
    Join Date
    Dec 2004
    Posts
    29

    help about while loop

    Hi@all

    I wrote a program to read one line intergers and hold them in an array after that echo them. My while loop should end either my array is full or when I hit enter.My problem is when I hit enter, loop doesn't end . I am sending my code. Can anyone tell me what is wrong in my code? I am using g++ compiler...


    Code:
    #include <iostream>
    using namespace std;
    int main()
    {
            const int size=10; //array size
            int array[size]; //declaration
            int input;  //input
            int actual=0; // counter how many numbers are read until eof
            input=cin.get(); //read nembers
            while (input!=cin.eof()&&actual<size) //loop ends when user hit enter or array is full
            {
                   array[actual]=input;
                   actual++;
                   input=cin.get();
             }
             for (int i=0; i<actual; i++)
             cout <<a[i];
    return 0;
    }
    thanks
    Last edited by Apropos; 12-10-2004 at 06:03 PM.

  2. #2
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    Posts
    9,897
    >input=cin.get(); //read nembers
    This doesn't read numbers, it reads characters.

    >input!=cin.eof()
    cin.eof() doesn't work like this. It returns true if end-of-file has been reached after a read failure.

    Try something more like this:
    Code:
    #include <iostream>
    
    using namespace std;
    
    int main()
    {
      const int size = 10;
      int array[size];
      int actual = 0;
      int input;
    
      while (cin>> input && actual < size) {
        array[actual] = input;
        actual++;
      }
    
      for (int i = 0; i < size; i++)
        cout<< array[i] <<endl;
    }
    You can use cin>>input as a loop condition because it returns a value that's convertable to bool and meaningful when you do. As long as cin>>input returns true, a number was read and nothing bad happened.

    [edit]
    Just so you know (and to avoid a future question), the two tests in the loop condition really should be reversed. But I'll leave it to you to figure out why.
    [/edit]
    Last edited by Prelude; 12-10-2004 at 06:16 PM.
    My best code is written with the delete key.

  3. #3
    Registered User
    Join Date
    Dec 2004
    Posts
    29
    @Prelude

    Thanks for help but the way that you suggested me doesn't work for me because when I type less than 10 numbers, loop doesn't end. It ends until my array is full. I want to my loop ends when I hit enter.

    example;

    assume I enter four numbers like 1234 and hit enter output should like 1234.

    Thanks
    Last edited by Apropos; 12-10-2004 at 06:28 PM.

  4. #4
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    Posts
    9,897
    >assume I enter four numbers like 1234 and hit enter output should like 1234
    If you want to allow anything more than single digit numbers, there must be some intervening whitespace between them. But to get a program meeting that specification, you would do something equivalent to this:
    Code:
    #include <iostream>
    
    using namespace std;
    
    int main()
    {
      const int size = 10;
      char array[size];
      int actual = 0;
      char input;
    
      while (actual < size && cin.get(input) && input != '\n') {
        array[actual] = input;
        actual++;
      }
    
      for (int i = 0; i < actual; i++)
        cout<< array[i];
      cout<<endl;
    }
    Notice how the program now works with char instead of int.
    My best code is written with the delete key.

  5. #5
    Registered User
    Join Date
    Dec 2004
    Posts
    29
    Yes . I wrote almost the same program for char. Now, I am trying to write the same prog. for integers. I guess cin skips whitespace so my loop doesn't end when I hit enter. I should use another code instead of cin right?

    thanks

  6. #6
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    Posts
    9,897
    >I should use another code instead of cin right?
    Yes and no. You should still use cin, but this time for string input instead of either character or integer input. This way you can read an entire line (up to the [Enter]), and parse it using a myriad of techniques. Stringstreams are the most elegant though:
    Code:
    #include <iostream>
    #include <sstream>
    #include <string>
    
    using namespace std;
    
    int main()
    {
      const int size = 10;
      string line;
    
      getline(cin, line);
    
      int actual = 0;
      istringstream in(line);
      int array[size];
      int input;
    
      while (actual < size && in>>input) {
        array[actual] = input;
        actual++;
      }
    
      for (int i = 0; i < actual; i++)
        cout<< array[i];
      cout<<endl;
    }
    Now you can type
    Code:
    1 2 3 4
    And the output will be
    Code:
    1234
    You no longer have to worry about the quirks of the >> operator for cin because you do your own parsing and conversions. You'll find this done in most real world code because it offers the most flexibility and the least risk of error through misunderstanding.
    My best code is written with the delete key.

  7. #7
    Registered User
    Join Date
    Dec 2004
    Posts
    29
    @thanks for your help

    I think I should read my book now I am confuse about cin, cin.get and cin.getline

    just curiosity, is there anyway to write this code without using a string.

    thanks

  8. #8
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    Posts
    9,897
    >I am confuse about cin, cin.get and cin.getline
    cin is an object, cin.get and cin.getline are functions (as is cin>>, even if it doesn't look like it). That's the first thing you need to remember. get can be confusing because it's overloaded to do so many different things. A good reference will do you wonders.

    >is there anyway to write this code without using a string
    Yes. You don't want to do it though, at least not until you're more comfortable with the language. If you avoid using strings of any sort then you're stuck with either the formatted input of cin>>, or character-by-character input. We've already established that the former isn't suitable in this case, so you would be forced to use the latter. That involves parsing the input stream character-by-character as they come and performing a manual integer conversion. The first is tricky and the second is non-trivial when done correctly.

    It's a fun little exercise in low level hacking though. Give it a try when you feel comfortable.
    My best code is written with the delete key.

  9. #9
    Toaster Zach L.'s Avatar
    Join Date
    Aug 2001
    Posts
    2,686
    It could be, but your code would either be non-portable (system specific code dealing with grabbing input, for example), or non-scalable. An example of the latter is here:
    Code:
    #include <iostream>
    int main()
    {
       unsigned int inp;
       std::cin >> inp; // Although, this should really read in a string.
                        // You will have problems if the user enters a non-integer.
                        // Test it and you will see why. (Hence, Prelude's
                        // code is much better, but this is an 'absolutely no string'
                        // solution).
       while(inp)
       {
          std::cout << (inp % 10)) << std::endl;
          inp /= 10;
       }
    }
    Now, to see why this should not be prefered, enter a large number: 123456787654321, for example, and see what you get.

    *edit*
    And Prelude beat me to it...
    The word rap as it applies to music is the result of a peculiar phonological rule which has stripped the word of its initial voiceless velar stop.

  10. #10
    Registered User
    Join Date
    Dec 2004
    Posts
    29
    Quote Originally Posted by Zach L.
    Now, to see why this should not be prefered, enter a large number: 123456787654321, for example, and see what you get.
    I see what happened. Thanks Prelude and Zach L. I appreciate for your help.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. nested loop, simple but i'm missing it
    By big_brother in forum C Programming
    Replies: 19
    Last Post: 10-23-2006, 10:21 PM
  2. While loop misbehaving (or misunderstanding)
    By mattAU in forum C Programming
    Replies: 2
    Last Post: 08-28-2006, 02:14 AM
  3. loop in a linked linked lists
    By kris.c in forum C Programming
    Replies: 6
    Last Post: 08-26-2006, 12:38 PM
  4. while loop help
    By bliznags in forum C Programming
    Replies: 5
    Last Post: 03-20-2005, 12:30 AM
  5. loop issues
    By kristy in forum C Programming
    Replies: 3
    Last Post: 03-05-2005, 09:14 AM