I'm trying to use C#'s Console.ReadLine() method to take user input from the console, then subsequently print text on the same line.
Code being used:
using System;
namespace Test {
class Program {
static void Main(string[] args) {
Console.ReadLine();
Console.Write(" out");
}
}
}
What I'm expecting from the console:
in out
What's actually being produced:
in
out
Note that in here is being typed into the console.
Any assistance would be greatly appreciated. Thanks!
-chris
The problem is that it automatically echoes the user input, including the newline when the enter key is pressed. So you have to stop it from echoing the input and handle that yourself.
You can do this by using Console.ReadKey(Boolean) and passing true to intercept the key, and only write it to the output if it's not the enter key.
That would look like this:
using System;
namespace Test {
class Program {
static void Main(string[] args) {
while (true) {
var key = Console.ReadKey(true);
if (key.Key == ConsoleKey.Enter) {
break;
} else {
Console.Write(key.KeyChar);
}
}
Console.WriteLine(" out");
}
}
}
Related
i'm really new to C# and i've been working on this really simple command line style program (that has custom commands and such). Now the commands work great but every time I allow the user to go back to enter another command or just anything it closes the program when I press enter. But only the second time I execute a command. I think this has something to do with console.WriteLine();
Here's my code (I've searched everywhere on how to fix this and nothing that i've found has worked)
using System;
namespace ConsoleProgram
{
class Program
{
private static string userEnteredCommand;
static void Main(string[] args)
{
Console.Title = "IAO Systems Service Console";
onCommandLineStart();
void onCommandLineStart()
{
Console.WriteLine("Copyright (C) 2018 IAO Corporation");
Console.WriteLine("IAO Systems Service Console (type 'sinfo' for more information.");
userEnteredCommand = Console.ReadLine();
}
void onCommandLineReturn()
{
userEnteredCommand = Console.ReadLine();
}
// Commands
if (userEnteredCommand == "sinfo")
{
Console.WriteLine(" ");
Console.WriteLine("Program information:");
Console.WriteLine("Created for IAO Corporation, by Zreddx");
Console.WriteLine("This program controls doors, gates and e.t.c within IAO Terratory.");
Console.WriteLine(" ");
Console.WriteLine("This program is protected by copyright, do not redistribute. ");
}
else
{
Console.WriteLine("That command does not exist, do 'programs' for a list of actions.");
}
onCommandLineReturn();
}
}
}
Console applications close when they get to the end of Main. It's exiting after the Console.ReadLine in onCommandLineReturn();.
Add a bool variable called keepLooping, set it to true, and wrap your code in a while(keepLooping) statement. Somewhere in your program flow, check for input like "quit" or "exit" and set the keepLooping variable to false.
Here's an example of it in a dotnetfiddle: https://dotnetfiddle.net/Jguj5k
using System;
// Namespace
namespace ConsoleApp22
{
// Main Class
class Program
{
// Entry Point Method
static void Main(string[] args)
{
string name = "Florent Shomora";
// start here
Console.Write("Hello World"+ name);
}
}
}
This is my code and the problem is that the console pop up and die.
Do you want to see console window ? Try to use Console.Readline()
static void Main(string[] args)
{
string name = "Florent Shomora";
// start here
Console.Write("Hello World"+ name);
Console.Readline();
}
The problem is that your program works without error.
However, what does your program do? It prints a message to the screen, nothing more. This is a very fast operation. The program will complete this operation and terminate probably faster than you can read the message.
You can pause the program by adding another operation which will take more time, such as expecting user input:
string name = "Florent Shomora";
// start here
Console.Write("Hello World"+ name);
Console.ReadLine();
With that extra call to ReadLine() the application will now remain open and wait for you to press "return" before closing.
Try
Console.Readline()
it should show u the Console and u can exit by clicking for example enter
I know how to program Console application with parameters, example : myProgram.exe param1 param2.
My question is, how can I make my program works with |, example : echo "word" | myProgram.exe?
You need to use Console.Read() and Console.ReadLine() as if you were reading user input. Pipes replace user input transparently. You can't use both easily (although I'm sure it's quite possible...).
Edit:
A simple cat style program:
class Program
{
static void Main(string[] args)
{
string s;
while ((s = Console.ReadLine()) != null)
{
Console.WriteLine(s);
}
}
}
And when run, as expected, the output:
C:\...\ConsoleApplication1\bin\Debug>echo "Foo bar baz" | ConsoleApplication1.exe
"Foo bar baz"
C:\...\ConsoleApplication1\bin\Debug>
The following will not suspend the application for input and works when data is or is not piped. A bit of a hack; and due to the error catching, performance could lack when numerous piped calls are made but... easy.
public static void Main(String[] args)
{
String pipedText = "";
bool isKeyAvailable;
try
{
isKeyAvailable = System.Console.KeyAvailable;
}
catch (InvalidOperationException expected)
{
pipedText = System.Console.In.ReadToEnd();
}
//do something with pipedText or the args
}
in .NET 4.5 it's
if (Console.IsInputRedirected)
{
using(stream s = Console.OpenStandardInput())
{
...
This is the way to do it:
static void Main(string[] args)
{
Console.SetIn(new StreamReader(Console.OpenStandardInput(8192))); // This will allow input >256 chars
while (Console.In.Peek() != -1)
{
string input = Console.In.ReadLine();
Console.WriteLine("Data read was " + input);
}
}
This allows two usage methods. Read from standard input:
C:\test>myProgram.exe
hello
Data read was hello
or read from piped input:
C:\test>echo hello | myProgram.exe
Data read was hello
Here is another alternate solution that was put together from the other solutions plus a peek().
Without the Peek() I was experiencing that the app would not return without ctrl-c at the end when doing "type t.txt | prog.exe" where t.txt is a multi-line file. But just "prog.exe" or "echo hi | prog.exe" worked fine.
this code is meant to only process piped input.
static int Main(string[] args)
{
// if nothing is being piped in, then exit
if (!IsPipedInput())
return 0;
while (Console.In.Peek() != -1)
{
string input = Console.In.ReadLine();
Console.WriteLine(input);
}
return 0;
}
private static bool IsPipedInput()
{
try
{
bool isKey = Console.KeyAvailable;
return false;
}
catch
{
return true;
}
}
This will also work for
c:\MyApp.exe < input.txt
I had to use a StringBuilder to manipulate the inputs captured from Stdin:
public static void Main()
{
List<string> salesLines = new List<string>();
Console.InputEncoding = Encoding.UTF8;
using (StreamReader reader = new StreamReader(Console.OpenStandardInput(), Console.InputEncoding))
{
string stdin;
do
{
StringBuilder stdinBuilder = new StringBuilder();
stdin = reader.ReadLine();
stdinBuilder.Append(stdin);
var lineIn = stdin;
if (stdinBuilder.ToString().Trim() != "")
{
salesLines.Add(stdinBuilder.ToString().Trim());
}
} while (stdin != null);
}
}
Console.In is a reference to a TextReader wrapped around the standard input stream. When piping large amounts of data to your program, it might be easier to work with that way.
there is a problem with supplied example.
while ((s = Console.ReadLine()) != null)
will stuck waiting for input if program was launched without piped data. so user has to manually press any key to exit program.
This is my PHP code for passing data to a C# exe file.
<?
shell_exec("p3.exe --tRyMe");
?>
What I want is, I'll post a string to p3.exe file, and that exe file prints "tRyme" string to the screen.
using System;
using System.Collections.Generic;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string a;
Console.Write("Please enter a string : ");
a = Console.ReadLine();
Console.WriteLine("You have entered: {0}", a);
Console.ReadKey();
}
}
}
And this is my C# code.
I've tried "--tRyMe", "-tRyMe", "tRyMe" etc. to do that but, this code prints only "Please enter a string" to the screen.
What I want is see the output like:
You have entered: tRyMe
Can you help me with doing that?
Best wishes.
I can't discuss the PHP code, but in the c# side, you need to check the number of arguments passed to your program from the command line and if there is an argument, don't ask for input, but print the argument received
static void Main(string[] args)
{
string a;
if(args.Length == 0)
{
Console.Write("Please enter a string : ");
a = Console.ReadLine();
}
else
a = args[0];
Console.WriteLine("You have entered: {0}", a);
Console.ReadKey();
}
Without having tried it, does a pipe work?
<?php
shell_exec("echo tRyMe | p3.exe");
?>
you could only run an application and print the output but you can not interact with the application - Console.ReadLine() expects an input ...
so you can't use it (affects also Console.ReadKey())
try this:
static void Main(string[] args)
{
string a;
if(args.Length == 0)
a = "No arg is given";
else
a = args[0];
Console.WriteLine("You have entered: {0}", a);
}
I know how to program Console application with parameters, example : myProgram.exe param1 param2.
My question is, how can I make my program works with |, example : echo "word" | myProgram.exe?
You need to use Console.Read() and Console.ReadLine() as if you were reading user input. Pipes replace user input transparently. You can't use both easily (although I'm sure it's quite possible...).
Edit:
A simple cat style program:
class Program
{
static void Main(string[] args)
{
string s;
while ((s = Console.ReadLine()) != null)
{
Console.WriteLine(s);
}
}
}
And when run, as expected, the output:
C:\...\ConsoleApplication1\bin\Debug>echo "Foo bar baz" | ConsoleApplication1.exe
"Foo bar baz"
C:\...\ConsoleApplication1\bin\Debug>
The following will not suspend the application for input and works when data is or is not piped. A bit of a hack; and due to the error catching, performance could lack when numerous piped calls are made but... easy.
public static void Main(String[] args)
{
String pipedText = "";
bool isKeyAvailable;
try
{
isKeyAvailable = System.Console.KeyAvailable;
}
catch (InvalidOperationException expected)
{
pipedText = System.Console.In.ReadToEnd();
}
//do something with pipedText or the args
}
in .NET 4.5 it's
if (Console.IsInputRedirected)
{
using(stream s = Console.OpenStandardInput())
{
...
This is the way to do it:
static void Main(string[] args)
{
Console.SetIn(new StreamReader(Console.OpenStandardInput(8192))); // This will allow input >256 chars
while (Console.In.Peek() != -1)
{
string input = Console.In.ReadLine();
Console.WriteLine("Data read was " + input);
}
}
This allows two usage methods. Read from standard input:
C:\test>myProgram.exe
hello
Data read was hello
or read from piped input:
C:\test>echo hello | myProgram.exe
Data read was hello
Here is another alternate solution that was put together from the other solutions plus a peek().
Without the Peek() I was experiencing that the app would not return without ctrl-c at the end when doing "type t.txt | prog.exe" where t.txt is a multi-line file. But just "prog.exe" or "echo hi | prog.exe" worked fine.
this code is meant to only process piped input.
static int Main(string[] args)
{
// if nothing is being piped in, then exit
if (!IsPipedInput())
return 0;
while (Console.In.Peek() != -1)
{
string input = Console.In.ReadLine();
Console.WriteLine(input);
}
return 0;
}
private static bool IsPipedInput()
{
try
{
bool isKey = Console.KeyAvailable;
return false;
}
catch
{
return true;
}
}
This will also work for
c:\MyApp.exe < input.txt
I had to use a StringBuilder to manipulate the inputs captured from Stdin:
public static void Main()
{
List<string> salesLines = new List<string>();
Console.InputEncoding = Encoding.UTF8;
using (StreamReader reader = new StreamReader(Console.OpenStandardInput(), Console.InputEncoding))
{
string stdin;
do
{
StringBuilder stdinBuilder = new StringBuilder();
stdin = reader.ReadLine();
stdinBuilder.Append(stdin);
var lineIn = stdin;
if (stdinBuilder.ToString().Trim() != "")
{
salesLines.Add(stdinBuilder.ToString().Trim());
}
} while (stdin != null);
}
}
Console.In is a reference to a TextReader wrapped around the standard input stream. When piping large amounts of data to your program, it might be easier to work with that way.
there is a problem with supplied example.
while ((s = Console.ReadLine()) != null)
will stuck waiting for input if program was launched without piped data. so user has to manually press any key to exit program.