The Convert class and converting Console input C# - c#

This question is more of a "Why can't I do this/What am I doing wrong" as I have managed to accomplish what the program should do, but it raised more questions around why certain things work the way they do.
For starters, the goal of this project is to capture a single character from the Console window (using Console.Read()/.ReadLine()), convert it to a string with the Convert class, and then write it to the Console window.
I've managed to get my project to have this functionality with the following code:
namespace ReadConvertWrite
{
class Program
{
static void Main(string[] args)
{
String input = Console.ReadLine();
try
{
Convert.ToInt32(input);
}
catch (Exception)
{
}
Console.WriteLine(input);
Console.ReadLine();
}
}
}
Given that this seems like a pointless exercise since the conversion is unnecessary I wanted to make it necessary by using the .Read() method instead of .ReadLine(). Which leads me to my question:
Why is it that .Read() always prints the hexadecimal value of the character inputted into the console despite the MSDN documentation making it sound like .Read() and .ReadLine() work the same way apart from reading a single character Vs a line, and beyond that why do none of the Convert class methods I've tried (.ToInt, .ToString, etc) work to actually give me output other than the hexadecimal values?
Here's what I've tried so far:
namespace ReadConvertWrite
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine(Convert.ToString(Console.Read()));
Console.ReadLine();
Console.ReadLine();
}
}
}
And:
namespace ReadConvertWrite
{
class Program
{
static void Main(string[] args)
{
var input = 0;
input = Console.Read();
String InputString = Convert.ToString(input);
Console.ReadLine();
Console.ReadLine();
}
}
}

Console.Read returns an integer representing a character. Console.ReadLine returns a string.
When you do Console.WriteLine(Console.ReadLine()), you're simply echoing your input. When you do Console.WriteLine(Convert.ToString(Console.Read())), you're taking the numeric value of the character and printing it as a number.
Convert.ToString(int) will not interpret the integer as a character - that would be rather ridiculous. Would you expect Convert.ToString(42) to print *? You need to cast the integer to a character instead:
Console.WriteLine((char)Console.Read());
Most likely, you don't want to use Console.Read anyway - it's a rather specific thing dealing with old-school CLI, rather than anything very useful for a typical console program, unless you need to stream lots of characters and want to avoid allocating huge strings unnecessarily.
Make sure to handle end-of-file correctly - Console.Read() will return -1 when the input stream ends, which is not a valid value for char.

If you hover your mouse over Read() it will show you it returns an int, not a string. Converting an 'int' to a string will just be a string representation of an int. To get a character from an int, cast it back to a char.
The cast to a char will convert the number back into its character representation.
Console.WriteLine((char)Console.Read());

Related

Instant crash when trying to convert readline before any input has been made

I'm making a simple method where I'm going to use console input to pick a students number from a list, now for some reason the program crashes before I've pressed enter while reading the line and the VS tells me Input string was not in the correct format.
var whoisthestudent = Console.ReadLine();
int who = Convert.ToInt32(whoisthestudent);
So here's the part of the program that crashes, these are the first two lines of the method and when it crashes it gives me the format exception. I just can't figure out why it starts converting the readline before I've written anything or pressed enter?
Use int.TryParse to be on the safer side
Int studentId;
var whoisthestudent = Console.ReadLine();
If(int.TryParse(whoisthestudent, out studentId)
{
Console.WriteLine(studentId);
} else
{
Console.WriteLine("Failed to convert" );
}

C# Wrong Value stored in variable

I am fairly new to programming so have some mercy ;)
I am trying to build a program that can solve equations and give gradient and so on in c#, so I can make it more complex gradually. Problem is, there appears to be a wrong value from my input when I tried to start building it.
Console: Given value for "a":
9 The Output: 57
My Code:
using System;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Input an linear Eqasion in the following Pattern -- a * x + b");
Console.Write("Given value for \"a\":");
decimal aValue;
aValue = Console.Read();
Console.Write(aValue);
}
}
}
Console.Read() returns an int, but not in the way you think. It returns the numeric value of the typed character, not the human-intuitive interpretation of a character that coincidentally happens to be a number. Consider for example what it would return if you type a letter, or any other non-numeric character.
And what is the numeric (decimal) value for the character '9'? 57 is.
It sounds like you want to read the line, not the character. For example:
string aValue;
aValue = Console.ReadLine();
Console.Write(aValue);
Remember that you'll need to press return to send the line to the application.
If you'll later need the value to be numeric, you'll still want to input the string but will want to parse it. For example:
string aValue;
aValue = Console.ReadLine();
if (decimal.TryParse(aValue, out decimal numericValue)
{
Console.Write(numericValue);
}
else
{
// The value could not be parsed as a decimal, handle this case as needed
}
Console.Read returns the character code entered on the command line in this scenario. The ASCII character code of 9 is 57. If you're wanting numeric input, you'd be better using Console.ReadLine with Decimal.Parse (or better yet, Decimal.TryParse)
It is also worth noting that Console.Read only returns one character at a time, meaning for any inputs past 1 digit you'll need special handling. I highly recommend using ReadLine and parsing the string over handling converting the character codes to the number they represent.

Using PromptforLetter and DisplayLetter in C#

Below is a homeowrk assignment I've been working on.
I need to create a class called FormattedOutput in a file called FormattedOutput.cs. That class will have the following methods:
char PromptforLetter(void) - this method will return a value
void DisplayLetter(char letter) - this method will accept a value to display
Main should be in a file named mainModule.cs
Main will PromptforLetter for each character in your name and store each character into a char data type.
Then DisplayLetter(letter1) should display each letter as:
the actual letter
the decimal value of the key
the hexadecimal value of the key
the octal value of the key
the binary value of the key
Information should be displayed first...
Then prompts for each letter of your name.
Then a Table showing each value
Char Decimal Hex Octal Binary
Here is the horrible mess I have at this time
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
public class formattedOutput
{
char PromptforLetter(string prompt)
{
string value;
char achar;
Console.WriteLine("A", prompt);
Console.WriteLine("L", prompt);
Console.WriteLine("M", prompt);
Console.WriteLine("A", prompt);
Console.Read();
value = Console.ReadLine();
achar=Convert.ToChar(value.Substring(0,1));
return achar;
}
void DisplayLetter (char letter)
{
Console.WriteLine("A");
Console.Read();
I'm fairly uncertain of what you're going for, and it might help to clear up your introduction to the problem (or instance, we don't need to know filenames and such, just give the relevant details). It also seems like you're asking quite a few questions, so I'm going to focus on what I think you actually mean to ask.
The impression I'm getting is that you are to write a console application in C#, with a method to read a single character from user-input, then another one to echo it back to them using several number formats.
If that is, in fact, the case, you probably want something like this:
public char PromptforLetter(string prompt)
{
Console.Write(prompt + " "); // This prints out the prompt with a space, and no
// following line break
// Now you have a choice. Should you take the first key that is pressed, or
// should the user have to press enter?
// Option 1:
char ret = Console.ReadKey().KeyChar;
Console.WriteLine(); // Not necessary, but it improves user experience
return ret;
// Option 2:
return Console.ReadLine()[0]; // take the first indexed character from the
// string entered by the user. Strings have
// integer-indexers, so you can access single them
// characters in kind of like you would if they were
// a string array.
}
Printing the character is a bit simpler:
public void DisplayLetter(char val)
{
Console.Write("Char: {0}", val);
Console.Write("Decimal: {0}", (int)val);
Console.Write("Hex: {0:X}", (int)val);
Console.Write("Octal: {0}", Convert.ToString((int)val, 8));
Console.Write("Binary: {0}", Convert.ToString((int)val, 2));
}
Beyond that, it's mostly just up to you and what the instructor is looking for, specifically.

Console.ReadKey(false) in C# something fishy about it

i am trying to make a simple application in C# in which every character I type is displayed in a console window. Here is my code :
class Program {
static void Main(string[] args) {
while (true) {
System.ConsoleKeyInfo input;
input = Console.ReadKey(false);
String d = input.ToString();
char c = d[0];
Console.WriteLine(c);
}
}
}
The problem is that the characters are not displayed correctly, and to be more precise, every character is followed by an 'S'. For example i type 'a' and i get 'aS' instead of 'a'. Any solutions? Thnx in advance!
What you are seeing is the following:
The original character you entered, since you passed false not true to ReadKey
The first characters of the string "System.ConsoleKeyInfo", since the ToString() method returns the typename (here), not the character entered.
Use the following code instead to achieve what you attempted:
while(true)
{
ConsoleKeyInfo info = Console.ReadKey(true);
Console.WriteLine(info.KeyChar);
}
Because input.ToString() == "System.ConsoleKeyInfo" :-)
Depending on what you want to do, try writing input.KeyChar.
The parameter of Console.ReadKey(false); defines if the key you type is intercepted or not. So Console.ReadKey(false); prints the character you type and Console.Writeline(c) prints the S.
Try char c = input.KeyChar; instead.
The problem is that you are using ToString() on a System.ConsoleKeyInfo. When this is turned into a string you will get "System.ConsoleKeyInfo" and the first character is therefore 'S'. Did you mean to write the following code instead?
while (true)
{
var input = Console.ReadKey(false);
Console.WriteLine(input.KeyChar);
}
With that code each character will get duplicated (so you will get aabbccddee). Change the false to true in ReadKey to fix that.

Reading two Characters in C#

I cannot read a second character with Console.Read() method. I mean I don't get any Prompt to read the second character from Keyboard. Any help please? Also, I understand that character is by default an int but we still need to convert it to char when reading from input, is it right? The code below reads the first char but terminates with the second.
public static void Main()
{
Console.WriteLine("The First Character?:");
char firstChar=Convert.ToChar(Console.Read());
Console.WriteLine("The Second Character?:");
char secondChar=Convert.ToChar(Console.Read());
}
Looks like Console.ReadKey() is what you actually want.
Please see Console.Read. Specifically, this part:
The Read method blocks its return while you type input characters; it terminates when you press the Enter key. Pressing Enter appends a platform-dependent line termination sequence to your input (for example, Windows appends a carriage return-linefeed sequence). Subsequent calls to the Read method retrieve your input one character at a time. After the final character is retrieved, Read blocks its return again and the cycle repeats.
Perhaps this code is closer to what you're looking for...
public static void Main()
{
Console.WriteLine("The First Character?:");
char firstChar = Convert.ToChar(Console.ReadKey().KeyChar);
Console.WriteLine();
Console.WriteLine("The Second Character?:");
char secondChar = Convert.ToChar(Console.ReadKey().KeyChar);
}
Your second Console.Read() is consuming the carriage return terminating the first read.
Console.ReadKey is a bit friendlier to use, since it doesn't require a terminating carriage return. If you want to continue using Console.Read, you might try consuming and discarding the carriage return before the second prompt, like:
public static void Main()
{
Console.WriteLine("The First Character?:");
char firstChar = Convert.ToChar(Console.Read());
Console.Read(); // consume carriage return
Console.WriteLine("The Second Character?:");
char secondChar = Convert.ToChar(Console.Read());
Console.WriteLine(secondChar);
}

Categories