plumb crazy

bpayne111

Well-known member
Joined
Feb 28, 2003
Messages
326
Location
BFE
C#:
using System;

namespace DELETEONEDAY
{
	class Class1
	{
		[STAThread]
		static void Main(string[] args)
		{
			char[] userInput = new char[4];

		Console.WriteLine("Please input 4 numbers. (after each number press the enter key).");

		for(int x = 0; x <=3; x++)
		{
			userInput[x] = (char)Console.Read();
		}
		for(int x = 0; x <=3; x++)
		{
			Console.WriteLine(userInput[x]);
		}
		}
	}
}

this code looks simple enough... you may wonder why i posted it.

I run this code expecting to input 4 chars then displaying them on the screen...

It loops 4 times as expected but only prompts me for input twice??????
heres an example of what happens when i run it.

<user input: 1>
<user input:2>

program displays

1


2


the 2nd and 3rd Console.Read statements are run by the program but it does not pause for me to input the value.
im stumped.
(if you are wondering why i have made such a simple program its because this is actually a java program i must write for school. the results seemed so bizzare to me, i swithced over to C# and ran the same code again only to have the same results. we arent required to use the loops but only because we havent learned them yet... i thought i was good to go but.. maybe im wrong)

******edit***** problem sovled

ok so it works if i hit enter after i enter all 4 char... thats cool cuz it works...
but why is the user prompted twice if enter is pressed after each input char?

(im happy its fixed but confused as to what happens when the user screws up)

brandon
 
Last edited by a moderator:
i would suggest: use ReadLine


string input = Console.ReadLine();

after that you can parse the number:



Code:
private bool ParseToInt(string text, out int number)
{
  number = 0;

  try
  {
    number = Int32.Parse(text);
  }
  catch
  {
    return false;
  }

  return true;
}

if you dont like that out and want to return an int value then this is also ok but you dont know if the parsing failed.. so number = 0 would be the alternative if the parsing failes
 
the question at hand is why is the output from that code the way it is.

thanks for the help though
brandon
 
The problem is .Read() takes the next character from the input - including The CRLF pair.
e.g. If you type 1<enter> then 2<enter>
the buffer will be
userInput[0] = 1 //byte 49
userInput[1] = <CR> //byte 13
userInput[2] = <LF> //byte 10
userInput[3] = 2 //byte 50.

as NK2000 suggested use readline as this handles the CRLF automatically.
 
i forgot someting which could matter

always trim the userinput to go sure there are no hidden/invisible chars at end of line
 
Back
Top