Unable to display an input from a user using Console.ReadLine() - c#

I am new to C# and the .NET Code / VSCcode.
Currently using VSCode to run and build C# codes.
I am unable to take user input using Console.ReadLine() after declaring a particular variable to hold it. The terminal generates this error code at the end of the program:
The program '[4544] forth.dll' has exited with code 0 (0x0).
using System;
namespace forth
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
Console.WriteLine("This is the first program we are trying to build");
var name = Console.ReadLine();
Console.WriteLine("Hello " + name, "you successfully entered a name");
Console.WriteLine("Hello " + name, "you successfully entered a name");
Console.WriteLine("you can press enter to exit the program");
Console.ReadLine();
}
}
}
Output "please enter your name" and displays "Hello + the user's name"
The program should exist afterwards

Try moving the comma after name to inside the string, and appending the second string to the first:
Console.WriteLine("Hello " + name + ", you successfully entered a name");
At the moment you will be using the WriteLine(string, string) overload, when I think you just want WriteLine(string)

When you created your project you picked the wrong type. You need to pick "New Console Application".
Right now you are building a library and a library does not have a Main method. Well, it can have, but it's not called. So create a new project, pick the correct type and copy your code over.

Related

How to define separate function in C#?

Since the .NET version has been updated, there is no need to write entire C# code just to print 'Hello World!'. Just Console.WriteLine(); is enough. But what I could not understand, is how to define a new function outside Main()?
If I want to develop a separate function outside Main(), do I need to write entire code including using System; and namespaces and Main() function? I am talking about updated version which is C# v10.
Please, do enlighten me!
I hope this question is not much lengthy and you got idea regarding the problem.
Here is the code for your reference:
class Program
{
public static void Main(string[] args)
{
string? theWord;
System.Console.WriteLine("Enter the word");
theWord = Console.ReadLine();
System.Console.WriteLine("original string: " + theWord);
System.Console.WriteLine("middle character of " + theWord + " is " + test(theWord));
}
public static string test(string theWord)
{
int i = 1 - theWord.Length % 2;
return theWord.Substring(theWord.Length / 2-i, 1+i);
}
}
There are two important things to understand here:
Firstly, top-level statements and implicit using directives are entirely different features. So you can declare a class as normal, but still omit the using directives. Likewise if you don't want to declare a namespace, you don't have to - although these days you could just use a file-scoped namespace declaration, e.g. namespace MyNamespace; without indenting everything.
Secondly, even with top-level statements, you can write methods... but they're effectively local methods within the Main method, and come with all the restrictions that imposes (e.g. no overloading). Note that even with top-level statements for your entry point, you can still declare other classes elsewhere - it would be entirely reasonable to have a brief Program.cs using top-level statements just to get everything going, but use "regular" C# elsewhere in the project. Indeed, that's how the ASP.NET Core templates work these days.
As an example, given the sample code, you could write (slightly amended for naming and to avoid warnings):
System.Console.WriteLine("Enter the word");
string? input = Console.ReadLine();
if (input is null)
{
Console.WriteLine("No input");
return;
}
System.Console.WriteLine($"Original string: {input}");
System.Console.WriteLine($"Middle character of {input} is {GetMiddle(input)}");
string GetMiddle(string input)
{
int i = 1 - input.Length % 2;
return input.Substring(input.Length / 2 - i, i + 1);
}
In this particular case you don't actually need the parameter for the method - input would be captured anyway, because GetMiddle is a local method.
You can write that like a normal method.
using System;
Console.WriteLine("Hello World");
display();
static void display()
{
Console.WriteLine("from display");
}

Can't seem to print a method in c# [duplicate]

This question already has answers here:
C# Creating and using Functions
(11 answers)
Closed 4 years ago.
I am trying to make a simple program that makes a list of words then it picks a random word and then it prints that word. Everything works but I just can't seem to make the program print the word. This is my code so far.
using System;
using System.Collections.Generic;
namespace Hangman
{
class Program
{
List<String> words = new List<String> { "cat", "police", "conjuring", "sand", "hoppleflink", "defenestrait", "cumberground", "sexy shreck" };
public string PickRandom()
{
var random = new Random();
var wordCount = words.Count;
var randomNum = random.Next(wordCount);
var randomWord = words[randomNum];
return randomWord;
}
static void Main(string[] args)
{
Console.WriteLine();
}
}
}
To make your code work, you need to print a value rather than nothing, as you currently are.
At the moment, your words field and PickRandom method are instance members, so Main (a static method) cannot use them without an instance of Program. So, first, we'll create an instance of Program:
Program program = new Program();
Then we'll take a random word:
string word = program.PickRandom();
And finally we'll write it:
Console.WriteLine(word);
Putting it all together:
static void Main(string[] args)
{
Program program = new Program();
string word = program.PickRandom();
Console.WriteLine(word);
// keep the console open after the code has executed by waiting for a keypress
Console.WriteLine("Press any key to continue...");
Console.ReadKey();
}
You can read about static vs instance members here.
You'll probably run up against an issue with Random soon - if you call your PickRandom method too frequently, you'll find that you get the same value repeated. The reason why is explained in this post. TL;DR: The seed value is based on time, so if you create two instances of Randomat the exact same time, you'll get the same seed value.

C# Simple "Hello World" in console missing a line of code?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp2
{
class Program
{
static void Main(string[] args)
{
string userName = "";
int userAge = 0;
int currentYear = 0;
Console.Write("Please enter your name: ");
userName = Console.ReadLine();
Console.Write("Please enter your age: ");
userAge = Convert.ToInt32(Console.ReadLine());
Console.Write("Please enter the current year: ");
currentYear = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Hello World, my name is {0} and I'm {1} years old, I was born on the year {2} .", userName, userAge, currentYear - userAge);
}
}
}
It is missing the last Console.WriteLine for some reason, after I enter the currentYear, it closes the application without displaying the string to the console. Im just now starting to learn c# so also any other sources to help me learn are also welcome, thanks! (btw im using visual studio)
You need to add Console.Read or Console.ReadLine at the bottom of your code
Console.ReadLine();
Or else the console will close because the blocks of codes has already been executed.
Side Note : Possible Duplicate of this Question
Why is the console window closing immediately without displaying my output?

I want to know how to perform input and output operations in C#

I want to know how to perform input and output operations in C#. I know C++ but I want to write a code in C#. This is the basic code in C++. I want to write the same thing using C# language.
#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
char name;
cout<<"\n Enter name";
cin>>name;
cout<<"Hello!!"<<name<<": \t ";
getch();
}
You can use Console.WriteLine and Console.ReadLine:
static void Main(string[] args)
{
Console.Clear()
string name;
Console.WriteLine("Enter Name: ");
name = Console.ReadLine();
Console.WriteLine("Hello! {0}:\t", name);
Console.ReadKey();
}
To output your result to the Console then you can use
Console class and use it's function like
public static void Main()
{
Console.Clear();
char name;
Console.WriteLine("Enter name");
name=Console.ReadLine();
Console.WriteLine("Hello!!"+name+": \t ");
Console.ReadKey();
}
if you want to redirect the output to file or other options you need to check for StreamWriter and StreamReader or other Stream Classes

C# Pass a file via command line

My Programm is supposed to read the file and count the number of vowels and consonants in it. So, the fileName must be passed as a command line argument. This is part of my code:
class FileDetails
{
static void Main(string[] args)
{
Console.WriteLine(args.Length);
foreach (string arg in args)
{
Console.WriteLine(arg);
}
}
}
After compilation of this file, I run it via command line and pass some arguments to the Main function:
C:\Users\StepN\Desktop\FILEDETAILS>filedetails abc def xyz
The result of programm looks like this:
3
abc
def
xyz
So, the root of the problem is that I need to pass as a command line argument the filename, but I don't know, how to do it.
Thanks in advance for any help!
The only problem you can have is file name with white spaces. If your file has name abc def xyz then you should pass it wrapped in double quotes:
C:\Users\StepN\Desktop\FILEDETAILS>filedetails "abc def xyz"
If you are using spaces in one command line argument then enclose it with double quotes. That is how you should give arguments to your executable:
C:\Users\StepN\Desktop\FILEDETAILS>filedetails.exe "C:\file name.txt"
In Code access filename:
class FileDetails
{
static void Main(string[] args)
{
if(args.Length > 0 )
{
string filePath = args[0];
//read the file using System.IO namespace
}
}
}
class Program
{
static void Main(string[] args)
{
if (args.Length == 0){
Console.WriteLine("Please pass command line arguments.");
return;
}
string fileName = args[0];
}
}
There is a way to do.
1) Open Notepad and write your code and save it.
2) MOST IMPORTANT: Open visual studio command prompt and compile the code as follow:
(i) Set current path, where your program is saved.
(ii) Compile it with csc FileName.cs
3) Now execute the program using following command line argument:
(a) FileName arg1 arg2
If you aren't comfortable doing this then create a batch file and pass write your arguments. Then run your .bat file which will trigger your C# program. I mean that this might trigger the .exe in your bin folder.

Categories

Resources