C# console application executing code when Console.ReadLine() executes - c#

I'm currently messing around with a Console application and I have some logic to get user input for 3 different things. I have the application designed so that the user can type 'Q' or 'q' at any time to exit the program. However, the way I am currently accomplishing this is through if statements after each user input (using the Console.ReadLine().)
A solution I thought of that would be better is to have a piece of code in one place that exits the program and is called automatically when the ReadLine() is executed and checks the input to see if it is 'q' or 'Q'. I was curious if there was any way to do something like this???
Here is the code I have now
Console.WriteLine("Please give me a source and destination directory...(Enter 'Q' anytime to exit)");
Console.Write("Enter source path: ");
_sourcePath = Console.ReadLine();
if (_sourcePath.Equals("q", StringComparison.CurrentCultureIgnoreCase))
{
Environment.Exit(Environment.ExitCode);
}
Console.Write("Enter destination path: ");
_destinationPath = Console.ReadLine();
if (_destinationPath.Equals("q", StringComparison.CurrentCultureIgnoreCase))
{
Environment.Exit(Environment.ExitCode);
}
Console.Write("Do you want detailed information displayed during the copy process? ");
string response = Console.ReadLine();
if (response.Equals("q", StringComparison.CurrentCultureIgnoreCase))
{
Environment.Exit(Environment.ExitCode);
}
if (response?.Substring(0, 1).ToUpper() == "Y")
{
_detailedReport = true;
}
It would be nice to remove the if blocks and just have the incoming value from the Console.ReadLine() checked when it is executed...

You can create a function to get the user's input and after the Console.ReadLine() just do any processing (exiting on 'q') on the input before returning it.
static void Main(string[] args)
{
Console.Write("Enter source path: ");
var _sourcePath = GetInput();
Console.Write("Enter destination path: ");
var _destinationPath = GetInput();
Console.Write("Do you want detailed information displayed during the copy process? ");
var response = GetInput();
var _detailedReport = response?.Substring(0, 1)
.Equals("y", StringComparison.CurrentCultureIgnoreCase);
}
private static string GetInput()
{
var input = Console.ReadLine();
if (input.Equals("q", StringComparison.CurrentCultureIgnoreCase))
Environment.Exit(Environment.ExitCode);
return input;
}

I'm afraid there's no direct way to hook into the ReadLine() call. Wrapping it all in your own method called 'ReadLine' could work though, say something like
static string ReadLine()
{
string line = Console.ReadLine();
if (line.Equals("q", StringComparison.CurrentCultureIgnoreCase))
{
Environment.Exit(Environment.ExitCode);
}
//Other global stuff
return line;
}
//Elsewhere
Console.Write("Enter source path: ");
_sourcePath = ReadLine(); //Note: No 'Console.' beforehand. This is your method!
Console.Write("Enter destination path: ");
_destinationPath = ReadLine();
Console.Write("Do you want detailed information displayed during the copy process? ");
string response = ReadLine();
if (response?.Substring(0, 1).ToUpper() == "Y")
{
_detailedReport = true;
}

Related

Unbreakable loop

I am trying to break a loop by only inputing a white space but everytime I do this it keeps looping idk why is that. Is it probably by a logic problem or what is it because id what is going on/
Console.WriteLine("Please create a file with .doc .txt .pxt etc");
string fileName = Console.ReadLine();
writer1 = new StreamWriter($"{fileName}");
while (true)
{
while (choiceParsered == false && choiceRange == false)
{
Console.WriteLine("1) write a file");
Console.WriteLine(" 2. Copy a file ");
Console.WriteLine(" 3. Exit ");
choose = Console.ReadLine();
choiceParsered = int.TryParse(choose, out num);
}
if (choose == "1")
{
string writing = "m";
while (true)
{
Console.WriteLine("What do you want to drive on the file? write a blank space to finish");
writing = Console.ReadLine();
writer1.WriteLine(writing);
if (writing == " " || writing == "" )
{
break;
}
}
}
The problem is caused by this line
choiceParsered = int.TryParse(choose, out num);
Here you get true if the user types a valid input. Then, when you type "1" the variable choose is assigned and the code enters the second loop.
If you type a space or press enter the second loop exits without problems.
But then you never reenter the first loop because the variable choiceParsered is true and, thus, the code goes to test again choose and this is still "1" so the code enters again the second loop and never ends
To fix you need to move the test for the choices inside the first loop AND set the choiceParsered again to false before exiting the input loop.
while (choiceParsered == false && choiceRange == false)
{
Console.WriteLine(" 1. write a file");
Console.WriteLine(" 2. Copy a file ");
Console.WriteLine(" 3. Exit ");
choose = Console.ReadLine();
choiceParsered = int.TryParse(choose, out num);
if(choiceParsered)
{
if (choose == "1")
{
string writing = "m";
while (true)
{
Console.WriteLine("What do you want to drive on the file? write a blank space to finish");
writing = Console.ReadLine();
writer1.WriteLine(writing);
if (writing == " " || writing == "")
{
choiceParsered = false;
break;
}
}
}
}
But there is still the problem of the outer infinite loop. This will never ends if you cannot put a break to terminate it or set a condition to end if
Console.WriteLine("Please create a file with .doc .txt .pxt etc");
string fileName = Console.ReadLine();
writer1 = new StreamWriter($"{fileName}");
bool exitProgram = false;
while (!exitProgram)
{
....
if (choose == "3")
exitProgram = true;
}
Also you never close the StreamWriter. This is a very serious bug that leaves the file open and without a proper flush to end the writing.
But you can have the using statement to close the file for you, so replace the line that opens the file with
using writer1 = new StreamWriter($"{fileName}");
I assume you mean that it doesn't break out of the first while(true) loop. In that case it is because the break instruction you have only breaks out of the second while(true) loop. You'll need to either use a goto statement or some other logic. I think also you would want to do writing == null instead of writing == "".

This code for tire pressure keep running off the screen

The code I have doesn't work with console.writeline
I'm not to use console.readline
[] tirePressure = new int [4];
string valueTestFail = "Get you tire check as soon as possible.";
Console.WriteLine("Let check your tires!\r\nPlease enter the pressure for the front right tire.");
string frontRightTire = Console.ReadLine();
while(!int.TryParse(frontRightTire, out tirePressure[0])){
Console.WriteLine(valueTestFail);
frontRightTire = Console.ReadLine();
} Console.WriteLine("Please Enter the pressure for the front left tire.");
string frontLeftTire = Console.ReadLine();
while(!int.TryParse(frontLeftTire, out tirePressure[1])){
Console.WriteLine(valueTestFail);
frontLeftTire = Console.ReadLine();
}
Console.WriteLine("Please Enter the pressure for your rear right tire.");
string rearRightTire = Console.ReadLine();
while(!int.TryParse(rearRightTire, out tirePressure[2])){
Console.WriteLine(valueTestFail);
rearRightTire = Console.ReadLine();
}
Console.WriteLine("Please enter the value of the rear left tire.");
string rearLeftTire = Console.ReadLine();
while(!int.TryParse(rearLeftTire, out tirePressure[3])){
Console.WriteLine(valueTestFail);
string rearLeftTire = Console.ReadLine();
}
if(tirePressure[0]==tirePressure[1] && tirePressure[2]==tirePressure[3]){
Console.WriteLine("The tires pass spec!");
}else{
Console.WriteLine("Get your tires checked out.");
}
The error code so long, the code just run the entire screen and I just want to console.writeline this code line
it sounds like you are trying to use a Windows .NET feature in Xamarin. I Googled "console writeline xamarin" and got some alternatives. Try System.Diagnostics.Debug.WriteLine(), for instance.
You might look at this URL, https://forums.xamarin.com/discussion/18387/equivalent-of-console-writeline, to see if the information there is able to help you out.
I've been using C# for over 10 years, I read through your C# code, and I don't see anything incorrect with it... if it's running on Windows. You might improve its style, but that's not what you're looking for, is it.

How do I use if else statements in c#?

I'm from a python background and I'm finding it difficult to pick up the syntax in c#.
I'm trying to write code so that the program will continuously ask the user for input and it will echo it on the screen, but if the user input is 'exit' then it exits.
I tried
Console.WriteLine("Hello World!");
Console.Write("Enter some text: ");
string userinput = Console.ReadLine();
if (userinput == "exit")
{
Console.ReadKey();
}
else
{
Console.WriteLine(userinput);
But it doesn't achieve expected results
An if statement only executes once.
Since you're looking to take some action repeatedly, a do/while construct is more along the lines of what you need.
Something like this should at least get you started in the right direction:
string userinput;
do
{
Console.Write("Enter some text: ");
userinput = Console.ReadLine();
Console.WriteLine(userinput);
}
while (userinput != "exit");

Console terminates after Console.Read(), even with Console.ReadLine() at the end

The following code asks for your name and surname.
class Program
{
static void Main(string[] args)
{
Console.Write("Enter your name: ");
string s = Console.ReadLine();
Console.WriteLine("Your name: " + s);
Console.Write("Enter your surname: ");
int r = Console.Read();
Console.WriteLine("Your surname: " + r);
Console.ReadLine();
}
}
After entering the name, the program successfully displays your input. However, after entering a surname, the program stops immediately. From my understanding, Console.Read() should return an int value of the first character of the string I enter (ASCII code?).
Why does the program terminate right after Console.Read()? Shouldn't Console.ReadLine() ensure the program stays open? I am using Visual Studio 2012.
When you tell the console to enter your surname you are asking for a single character.
Console.Write("Enter your surname: ");
int r = Console.Read();
This surely should be a ReadLine followed by another ReadLine before exit. You are probably entering the first character (into Read), followed by subsequent characters, then hitting enter to accept the surname but you are actually on the ReadLine that will exit. So:
class Program
{
static void Main(string[] args)
{
Console.Write("Enter your name: ");
string s = Console.ReadLine();
Console.WriteLine("Your name: " + s);
Console.Write("Enter your surname: ");
// change here
string surname = Console.ReadLine();
Console.WriteLine("Your surname: " + surname);
Console.ReadLine();
}
}
The program does not terminate after int r = Console.Read() for me.
Based on how the console application was run it will execute all the lines of code and then 'return'. Once done this will close the program as for all intents and purposes it has done what it needs to. It isn't going to sit around and be open when it has finished.
If you want it to keep the window open write Console.Readline() at the end and it will stay open, until some input has been done. I remember having this issue when I started out, and it's not a matter of the program closing unexpectedly, but rather you wanting to see the results in the console before it closes.

Passing data to executable file with PHP

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);
}

Categories