Why is my foreach printing out 2 char? - c#

I am trying to create an encryption (ceasar) for education and for some reason I can't seem to understand why my simple code (so far) is making such a hazzle
static void Main(string[] args)
{
string word;
int key = 0;
Console.WriteLine("Write your messages");
word = Console.ReadLine();
Console.WriteLine("Enter your key cypher");
key =int.Parse(Console.ReadLine());
encrypt(word, key);
}
static void encrypt(string message, int key)
{
foreach (char otherword in message)
{
Console.Write(otherword);
Console.Read();
}
}
If I write for example test after "Write your messages" and then place it into my string word and the use it in my function encrypt, it should output
t
e
s
t
but for whatever god forsaken reason I get output like this
t
es
t
and I dont understand why.

You probably want to use Console.WriteLine(otherword); then. The spacing of the newlines in the output is dependent on which key you press after the Console.Read(); line. (For example, if you press [Enter], then you will get a newline, but if you press A you will not.)
You should probably also use Console.ReadKey(true); rather than Console.Read(); as a method of separating your output, as this will make it so that the key you press does not show up.

You need to change Console.Read() to Console.ReadLine() in your encrypt function. Console.Read() only reads the next character from the input stream. And since pressing the enter key generates two characters: \r\n, it is looping twice.

In the encrypt method - change the Console.Write to Console.WriteLine and move the Console.Read() outside of the foreach.
static void encrypt(string message, int key)
{
foreach (char otherword in message)
{
Console.WriteLine(otherword);
}
Console.Read();
}

Use Console.ReadLine() instead of Console.Read() - or (even better) eliminate the line read entirely and use Console.WriteLine(otherword). Read() will mess with how the next line is formatted.

Related

How to enter the value in the same row along with the label in c# console application?

How to enter the value in the same row along with the label in c# console application?
When the user enter the value, expected to be
Enter the name: Testing
However in the current syntax, value : Testing comes in the second row. And also, how to validate the user to enter the value .. and not to press enter key without entering the values..
static void Main(string[] args)
{
Console.WriteLine("Enter the Name:");
string val = Console.ReadLine();
string str = val.ToString();
}
You want Console.Write() instead of Console.WriteLine().
Console.Write() and Console.WriteLine() both used for writing text on Console, but there is difference between both functions.
Console.Write(string) :
Writes the specified string value to the standard output stream.
Console.WriteLine(string) :
Writes the specified string value, followed by the current line
terminator, to the standard output stream.
In your case Console.WriteLine() wrote string to console with line terminator, i.e. \n, so Console.ReadLine() appeared on next line.
To read and write on same line, use Console.Write(), so it will not add \n to end of string
Your final code will look like,
static void Main(string[] args)
{
Console.Write("Enter the Name:");
//^^^^This need to updated
string val = Console.ReadLine();
string str = val.ToString();
}

The Convert class and converting Console input 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());

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