Jump to content

Question about C# user int input

- - - - -

This topic has been archived. This means that you cannot reply to this topic.
3 replies to this topic

#1
TheMagicalRock

TheMagicalRock

    Newbie

  • Members
  • Pip
  • 2 posts
Hello, I have been programming for about two weeks in c#, and I have one question, that I could not find by searching the web.

while coding a string input, it goes like:

string sname = Console.ReadLine();

Console.WriteLine("you just wrote {0}", sname);


My question though, is how you would do an input with an int value, like the user inputting a value for int x, or something like that. Thanks for any help given.

#2
Xav

Xav

    Writes binary right handed and hex left handed

  • Members
  • PipPipPipPipPipPipPipPipPip
  • 13,118 posts
By default, Console.ReadLine() returns a string value, regardless of what the user types. However, you can convert this to a string using the "int" object itself:

int x = int.Parse(Console.ReadLine());

 Console.WriteLine("you just wrote {0}", x);

Be careful, though. What if the user types something other than a number into the command prompt? In this case, you can use TryParse() to test if the line is a number:

string line = Console.ReadLine();

if (int.TryParse(line))

{

   int x = int.Parse(Console.ReadLine());

   Console.WriteLine("you just wrote {0}", x);

}

else

{

   Console.WriteLine("You didn't enter a number.")

}


The problem with this is that it will not keep asking for the piece of info. Consider this:

Console.WriteLine("Please enter your age:");

string line = Console.ReadLine()


while (!int.TryParse(line))

{

Console.WriteLine("This is not a valid number. Please enter again:");

line = Console.ReadLine();

}


int x = int.Parse(line);

Console.WriteLine("you just wrote {0}", x);

In this case, we use a "while" loop. If the user doesn't enter a valid number, the program asks for it again, until the user does enter an age. You might want to put an "if" statement in, to test whether or not the user wants to cancel.

Hope this helps,

Xav

#3
TheMagicalRock

TheMagicalRock

    Newbie

  • Members
  • Pip
  • 2 posts
Thank you, this helped a lot!

#4
Xav

Xav

    Writes binary right handed and hex left handed

  • Members
  • PipPipPipPipPipPipPipPipPip
  • 13,118 posts

TheMagicalRock said:

Thank you, this helped a lot!
No problem, Magical Stone (or Rock, whatever it is - I'm no good with names). Good luck with your C#!
Jordan said:

Good members, like yourself, stick around and post for ages to come!
Mr. Xav | Blog | Forums