-2

I have an assignment for college where I have to take strings as an input and stop the program if the user presses CTRL + z and then display the longest and shortest string. I got the Z alright but I can't seem to detect if the user pressed CTRL z.

I tried using (ki.Modifiers & ConsoleModifiers.Control) but it didn't work. here's the code

Console.Write("Enter a string: ");
String input = Console.ReadLine();
String l = input;
String s = input;
ConsoleKeyInfo ki = new ConsoleKeyInfo();

while (ki.Key != ConsoleKey.Z )
{
    Console.Write("Enter another string: ");
    input = Console.ReadLine();

    if (input.Length > l.Length) l = input;
    else if (input.Length < s.Length) s = input;
    Console.WriteLine("Press enter to continue or <CTRL> + Z to exit");
    ki = Console.ReadKey(true);
}
Console.WriteLine("Longest string: " + l);
Console.WriteLine("Shortest string: " + s);
Console.ReadLine();
Progman
  • 16,827
  • 6
  • 33
  • 48
  • Idk C# but in Java there are many event listeners like onKeyPressed, and in C++ there are event listeners like pressing() and pressed(). – Cole Henrich Nov 16 '22 at 20:08

1 Answers1

0

Learn how to use a debugger and debug. Here's what you may find if you set a breakpoint in line 16:

Debugger information

Put into code:

!(ki.Key == ConsoleKey.Z && ki.Modifiers == ConsoleModifiers.Control)

or simply

ki.KeyChar != 26

As mentioned by @Hans Passant in the comment, ReadLine() returns null when Ctrl+Z (and Enter) is pressed, so you can reduce your code to

Console.Write("Enter a string: ");
var s = Console.ReadLine();
var l = s;

while (true)
{
    Console.Write("Enter another string or Ctrl+Z to end input: ");
    string input = Console.ReadLine();
    if (input == null) break;

    if (input.Length > l.Length) l = input;
    else if (input.Length < s.Length) s = input;
}
Console.WriteLine("Longest string: " + l);
Console.WriteLine("Shortest string: " + s);
Console.ReadLine();
Thomas Weller
  • 55,411
  • 20
  • 125
  • 222
  • 1
    Windows uses Ctrl+Z, the unixes use Ctrl+D. Console.ReadLine() returns null when they are detected. – Hans Passant Nov 16 '22 at 20:47
  • can you give me the link where it shows what keychar 26 gives i was seeing it in the keys menu but couldn't find 26, and i've tried the first example before idk why it didn't work. thanks ig that will do – danytb8 Nov 16 '22 at 21:05
  • @danytb8: which link? You can see it in the debugger. You don't need a link, or if you need a link, that's a link to the ASCII table. We have control characters (like Ctrl-Key, you know) from 0 to 31, punctuation and numbers from 32 to 63, upper case from 64 to 95, lower case from 96 to 127. – Thomas Weller Nov 16 '22 at 21:11