In a console application,
I use a Console.Readline() to prompt,
It is only use to get an int (1 to 5),
However you can add more char than necessary.
How could I stop the prompt after record one char in my console please ?
You see this underscore _ .
I don't want to see it anymore.
Edit 01/10/15 10pm :
do
{
string ChoixString = Console.ReadLine();
Analyseur = int.TryParse(ChoixString, out ChoixInt);
} while (!Analyseur || ChoixInt <= 0 || ChoixInt >= 6);
Final goal : The user can't write more than one char in the prompt.
Solution :
ConsoleKeyInfo ChoixKey = Console.ReadKey();
string ChoixString = ChoixKey.Key.ToString();
Analyseur = int.TryParse(ChoixString, out ChoixInt);
Thanks for the help.
use this:
Console.ReadKey();
will read just one character/keypress
Related
Messing around with C# logic, trying to build a program where the user inputs a string, and then has the option to decide which letter is removed from said string.
Console.WriteLine("Please enter a string of letters");
string input = Console.ReadLine();
Console.WriteLine("please enter letters you would like removed");
char removedLetters = Convert.ToChar(Console.ReadLine());
foreach (char letter in input)
{
Console.WriteLine(input.Replace(removedLetters,' ').ToLower());
}
This works, but not entirely. I will get rid of characters, but only when written in a specific way that corresponds with the original input.
e.g helloworld -> remove l = he owor d
but helloworld -> remove elo = failure.
Can someone share some knowledge? Really trying to get better at logic, happy i got this far just need bit of guidance.
Cheers,
Andy
Expanding on Jasen's comment from earlier something like this ...
Console.WriteLine("Please enter a string of letters");
string input = Console.ReadLine();
List<char> input_array = input.ToList();
Console.WriteLine("please enter letters you would like removed");
string removedLetters = Console.ReadLine();
char[] remove_array = removedLetters.ToArray();
for (int k = 0; k < remove_array.Count(); k++)
{ input_array.RemoveAll(r=>r== remove_array[k]); }
Console.WriteLine(new string(input_array.ToArray()));
Again, using Linq, in this case RemoveAll, to automate the heavy lifting. I have not tested how efficient these are, they are quick and simple solutions not necessarily the most efficient.
Not sure how you want to handle duplicates but C# has an Except operator that works on Arrays. So convert both strings to an array and something like this should work...
Console.WriteLine("Please enter a string of letters");
string input = Console.ReadLine();
char[] input_array = input.ToArray();
Console.WriteLine("please enter letters you would like removed");
string removedLetters =Console.ReadLine();
char[] remove_array = removedLetters.ToArray();
char[] leftover_array = input_array.Except(remove_array).ToArray();
Console.WriteLine(new string(leftover_array));
This question already has answers here:
How to read char from the console
(4 answers)
Closed 4 years ago.
so the sample code of what I've done is here:
char regular = 'r';
char premium = 'p';
Console.WriteLine("Please enter your service (r or p:");
I am trying to get the user to input either r or p for the service they are have, but I don't know what to put under the "Console.WriteLine" to make it work with the char data types I entered. How do I fix this?
Also, specifically for the entering your service, it has to be in char, so says the problem that I'm working on.
edit*: I have tried using something like...
Console.Writeline("Please enter your service(r or p):")'
r= Convert.ToInt32(Console.ReadLine());
but because it's in char, I have a problem, I'm just not fully sure how to implement this in a way where I can get the user to type r or p
Thanks!
I would suggest to use string instead of char. Something like:
string regular = "r";
string premium = "p";
Console.WriteLine("Please enter your service (r or p:");
var input = Console.ReadLine();
if (input == regular )
{
//your reg logic here
}
else if (input == premium)
{
// your premium logic here
}
else
{
//handle case that none of above entered
}
You can ask for a single character of input from the user with Console.ReadKey()
This returns a ConsoleKeyInfo object which has a KeyChar property that will give you a character
char regular = 'r';
char premium = 'p';
Console.WriteLine("Please enter your service (r or p:");
var keyEntered = Console.ReadKey();
Console.WriteLine("\nYou chose " + keyEntered.KeyChar);
I want the user to first type a code (e.g. fkuk3463kj)
The array is limited to 20.
The rest must be filled with fillers.
Which filler the customer will use (e.g. #, t, z,7,_,0) is his own choice and he will asked to define it at the beginning right after the question for the code.
(hint: afterwards (or if possible directly) I have to decide (to complete the wish of customer) whether the filler has to be at the beginning or at the end.
(for example: fkuk3463kj########## or ##########fkuk3463kj)
Now I don't know how to implement this. I know, that it's not that difficult, but I don't get it! All my tryings were not really succesful.
Could anybody help me? This would be perfect!
And many thx in advance!
Console.WriteLine("Please type in your company number!");
string companyNr = Console.ReadLine();
string[] CNr = new string[companyNr.Length];
Console.WriteLine("Type a filler");
string filler= Convert.ToString(Console.ReadLine());
string[] fill = new string[filler.Length];
.
.
.
.
.
(please pardon my english...)
As far as I can see, you're working with string:
// Trim: let's trim off leading and trailing spaces: " abc " -> "abc"
string companyNr = Console.ReadLine().Trim();
which you want to Pad with some char up to the length length (20 in your case):
int length = 20;
string filler = Console.ReadLine().Trim();
// padding character: either provided by user or default one (#)
char pad = string.IsNullOrEmpty(filler) ? '#' : filler[0];
// shall we pad left: "abc" -> "##abc" or right: "abc" -> "abc##"
// I have to decide (to complete the wish of customer)
//TODO: whether the filler has to be at the beginning or at the end
bool leftPad = true;
string result = leftPad
? companyNr.PadLeft(length, pad)
: companyNr.PadRight(length, pad);
// in case you want a char array
char[] array = result.ToCharArray();
// in case you want a string array
string[] strArray = result.Select(c => c.ToString()).ToArray();
Since you are getting strings as an input you can use string padding. Look here: Padding Strings in the .NET Framework
You can write some method (or extension method):
string AppendString(string str, int count, char filler, bool fromStart)
{
return fromStart ? str.PadLeft(count, filler) : str.PadRight(count, filler);
}
I think this code should work for you.
Console.WriteLine("Please type in your company number!");
string companyNr = Console.ReadLine();
Console.WriteLine("Type a filler");
string filler= Convert.ToChar(Console.ReadLine());
string fill = companyNr.PadLeft(20,filler);
// or use string fill = companyNr.PadRight(20,filler);
Welcome to StackOverflow. I am also a beginner :)
int fixedLength = 20;
string mockupInput = "bladjiea";
string filler = "-";
While(mockupInput.Length < fixedLength)
{
mockupInput += filler;
}
This is easy beginner code that should work.
Lets make this a contest on who will write most beautiful code:
I'll start with the most trivial, brute method XD.
If you have the number:
int fillLength = 20 - companyNr.Length; //for example, 20 chars total.
You can fill a StringBuilder in a loop:
var sb = new StringBuilder()
for (int c = 0; c < fillLength; c++)
sb.Append(filler);
string result = companyNr + sb.ToString();
I'm new in the community and I'm learning C#. I try to write a program and faced with the problem below. I tried to find the answer in Google and here but no luck yet. When I choice "Y" I'm getting the error.
I attached the code and screenshot, please help if you can, thank you!
using System;
namespace YourAge
{
internal class Age
{
public static void Main()
{
DateTime newDataTime = DateTime.Now;
Console.WriteLine("So, today is " + "{0}", newDataTime);
Console.Write("Do you smoke a cigarettes? Y/N: ");
char Y = (char)Console.Read();
if (Char.IsUpper(Y))
{
Console.Write("How many cigarettes do you smoke in the day?: ");
int cigTotal = Convert.ToInt16(Console.ReadLine());
//cost of one cigarettes
float costOneCig = 0.3F;
float sumTotal = cigTotal * costOneCig;
Console.WriteLine("You are losing every day:{0:C2}", sumTotal);
}
else
//coming soon
Console.ReadKey();
}
}
}
This is the exception thrown:
The problem is that you are using Console.Read() instead of Console.ReadLine().
Console.Read() only reads the next character from standard input. Console.ReadLine(), on the other hand, reads the entire line of characters from the standard input stream and then moves to the next newline.
When you press 'Y' and then enter, when you get up to the next Console input, Convert.ToInt16(Console.ReadLine(), the Console is still up to the previous input line.
Possible solutions:
Change (char)Console.Read() to Covert.ToChar(Console.ReadLine()). ReadLine takes in an entire string, not a char, so you need to use Convert.ToChar instead of the simple (char) cast to convert the first character of the string into a char.
Add a blank Console.ReadLine() after (char)Console.Read() to tell the Console to flush to the next line.
Input your character together with the next number like "Y2" (although I highly doubt this is what you want to do).
string userInput = Console.ReadLine();
int numberOfCigarettes = Convert.ToInt16(userInput);
This might make it more visible for you what is the problem.
Console.ReadLine() returns a string which you later need to convert into an integer. If your userInput string is not a number, then conversion is impossible and an exception is thrown.
On the other hand your if statement is incorrect as well. Right now you are only checking the variable Y whether it is uppercase not whether it holds a literal character 'y'.
You could for example make sure that the variable Y is always uppercase like this:
if(Y.ToUpper().Equals('Y'))
You may want to try something like this so you can diagnose the problem. Please make sure to mark an answer if it is correct.
Console.Write("Do you smoke a cigarettes? Y/N: ");
string answer = Console.ReadLine();
while (answer.Length != 1) {
Console.WriteLine("Character is one letter silly.");
Console.Write("Do you smoke a cigarettes? Y/N: ");
answer = Console.ReadLine(); }
char response = answer[0];
if (response == 'Y' || response == 'y')
{
//YES RESPONSE
}
else
{
//NO RESPONSE
}
Console.ReadLine();
This code will let you know if you input anything else other than one character. Good luck with C#!
Basically I want 200 characters maximum to come up in Console.ReadLine() for user input before characters start being suppressed. I want it like TextBox.MaxLength except for console input. How would I go about this?
And I don't want to do input.Substring(0, 200).
Solved:
I used my own ReadLine function which was a loop of Console.ReadKey().
It looks like this, essentially:
StringBuilder sb = new StringBuilder();
bool loop = true;
while (loop)
{
ConsoleKeyInfo keyInfo = Console.ReadKey(true); // won't show up in console
switch (keyInfo.Key)
{
case ConsoleKey.Enter:
{
loop = false;
break;
}
default:
{
if (sb.Length < 200)
{
sb.Append(keyInfo.KeyChar);
Console.Write(keyInfo.KeyChar);
}
break;
}
}
}
return sb.ToString();
Thanks everyone
There is no way to limit the text entered into ReadLine. As the MSDN article explains,
A line is defined as a sequence of
characters followed by a carriage
return (hexadecimal 0x000d), a line
feed (hexadecimal 0x000a), or the
value of the Environment.NewLine
What you can do, is use ReadKey in a loop that does not allow going over 200, and breaks if the user keys Environment.NewLine.
If you can use Console.Read(), you can loop through until you reach the 200 characters or until an enter key is entered.
StringBuilder sb = new StringBuilder();
int i, count = 0;
while ((i = Console.Read()) != 13) // 13 = enter key (or other breaking condition)
{
if (++count > 200) break;
sb.Append ((char)i);
}
EDIT
Turns out that Console.ReadKey() is preferred to Console.Read().
http://msdn.microsoft.com/en-us/library/471w8d85.aspx