Thread: Yet another array question

  1. #1
    Registered User
    Join Date
    Sep 2005

    Yet another array question

    Ok I have spent hours trying to debug, STFW and the forums, looked at my beginers book until finally I decided to give up and harass you guys with another array question. You see I am writing my first program outside of book exercises (a program that will solve sudoku puzzles) and very early on I have ran into a bit of a snag:

    #include <iostream>
    int main(){
    int sudoku[9][9];
    int a, b;
    for(a = 0; a < 9; a++)
          cout<< "insert a number 1-9 for the cell ["<<a+1<<"]["<<b+1<<"] ";
    for(a = 0; a > -1 && a < 9; a++){
    cout<< sudoku[a][b];
    return 0;
    You see, when I enter the numbers 1-9 I get an output like this

    Why is it that the 1 and 2 are bunched together and how do I fix it?

  2. #2
    Registered User
    Join Date
    Jan 2005
    The reason each number is on a new line is because you added the cin.get() which waits for the user to hit enter before writing out the next number. The reason the first two numbers get written on the same line is because the first time through the cin.get() doesn't wait for the user to hit enter. The reason it doesn't wait is that there is already a character in the input stream that it can get. The reason that there is already a character in the input stream is that after the user enters each value in the array, they hit enter. That inserts the value into the appropriate place in the array, but it leaves a newline character in the stream. The next time through the initialization loop it ignores any whitespace because you are asking the user for an int with cin >>, so the extra newline doesn't cause any harm. However, the last time through the initialization loop, the newline remains in the stream. When the output loop is run, the cin.get() sees and gets this newline and doesn't wait for another, outputting the first and second value on the same line.

    One solution is to always add a cin.ignore() after using cin >> to ignore the trailing whitespace.

  3. #3
    Registered User
    Join Date
    Sep 2005
    Thanks again Daved. I'll post here again if I have anymore problems.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Dynamic Mutli dimensional Array question.
    By fatdunky in forum C Programming
    Replies: 6
    Last Post: 02-22-2006, 07:07 PM
  2. Class Template Trouble
    By pliang in forum C++ Programming
    Replies: 4
    Last Post: 04-21-2005, 04:15 AM
  3. Unknown Memory Leak in Init() Function
    By CodeHacker in forum Windows Programming
    Replies: 3
    Last Post: 07-09-2004, 09:54 AM
  4. Quick question about SIGSEGV
    By Cikotic in forum C Programming
    Replies: 30
    Last Post: 07-01-2004, 07:48 PM
  5. array question?
    By correlcj in forum C++ Programming
    Replies: 1
    Last Post: 11-08-2002, 06:27 PM