How do I receive and store data input in C#? - c#

Basically I'm still in the starting phase, and I know how to use Console.WriteLine, but I have no idea on how to have it read input from the user.
For example, I'd want a user to be able to type in a pair of numbers, then return the result.
My goal is a program that receives input , then combines them and returns the average.
This is all in Visual C# Express 2008

string input = Console.ReadLine();
that will return you a string of the user's input. Check out MSDN for documentation on the Console class. Also look at the Convert class.
int num = Convert.ToInt32(input);
Good luck new coder.

First create a variable to store the user input, like this:
int variablenameofyourchoice = 0;
Then take input like this and store it in your variable name:
variablenameofyourchoice = int.parse(Console.ReadLine())
Then do whatever you want with that variable. If you want two numbers do this twice.

This is a very general topic with a lot of answers, but Console.ReadLine is one counterpart of Console.WriteLine. It reads a line of text from standard in.

Have a look at Console.ReadLine() or Console.Read() in the MSDN Documentation

Related

Filter text in a variable

I have a variable (serial_and_username_and_subType) that contains this type of text:
CT-AF-23-GQG %username1% *subscriptionType*
DHR-345349-E %username2% *subscriptionType*
C3T-AF434-234-GQG %username3% *subscriptionType*
34-7-HHDHFD-DHR-345349-E %username4% *subscriptionType*
example: ST-NN1-CQ-QQQ-G12 %RandomDUDE12% *Lifetime*
after that, i have an IF instruction that checks if the user inputs something that is present in serial_and_username_and_subType.
if (userInput.Contains
(serial_and_username_and_subType))......
then, what i would like to do (but i am having troubles) is that when someone enters a serial, the program prints the corrispective username and subscription:
for example:
Please enter your Serial:
> ST-NN1-CQ-QQQ-G12
Welcome, RandomDUDE12!
You currently have a Lifetime subscription!
does anyone know a method or a way to obtain what i need?
You are already using Contains(). The other things you could use are
Substring()
Split()
IndexOf()
Split() is probably the easiest one as long as you can guarantee that neither % nor * are part of the serial, username or license:
var s = "ST-NN1-CQ-QQQ-G12 %RandomDUDE12% *Lifetime*";
var splitPercent = s.Split('%');
Console.WriteLine(splitPercent[1]);
var splitStar = s.Split('*');
Console.WriteLine(splitStar[1]);
This approach will work fine as long as you have few licenses only (maybe a few thousand are ok, because PCs are fast). If you have many licenses (like millions), you probably want to separate all that information so that it is not in a string, but a data structure. You would then use a dictionary and access the information directly, instead of iterating through all of them.

Parsing in CSharp - how to understand it

It's just few days ago that I jumped into learning C# and I already have one problem with understanding basics.. Maybe it's just the language barrier (I'm not English native speaker). Please, could you explain me how to understand parsing? For example: while creating a very simple calculator I wanted to read the first input number (which is a variable a). I use this code:
float a = float.Parse(Console.ReadLine());
and the same with b for the other number:
float b = float.Parse(Console.ReadLine());
I learnt that the float is a data type for decimals numbers so what exactly does this particular Parse() stands for?
Obviously, I tried to run the application without parsing and it wouldn't work because it reads it as string, but why? Thank you..
Console.ReadLine() returns a string, which represents a piece of text. So, from the computer's point of view, what you have after calling Console.ReadLine() is a piece of text. It may or may not contain the text "6.0", but from the computer's point of view, it is just a piece of text. As such, you cannot use it to add, subtract etc.
Using the float.Parse(...) method, you tell the computer: "This piece of text actually represents a floating point number, could you please read the text and give me back a number, so that I can start doing math with it?".
The method you are using, float.Parse() is just one of many such methods that take a String input value, and attempt to convert it into the target type, here a float.
There is a safer alternative, however, and it is TryParse():
float a;
if (float.TryParse(Console.ReadLine(), out a))
{
//do something with your new float 'a'
}
In either case, your are asking the framework to inspect the value you provide, and attempt to make a conversion into the requested type. This topic can be quite deep, so you'll want to consult MSDN for the specifics.
Console.ReadLine reads text that the user inputs and returns it to the program so that you may do with it what you want. Therefore, the ReadLine method returns a string.
If you want to work with a decimal (check the decimal class instead of float), you need to convert the string, which is a character sequence, to a number of your desired type, that's where float.Parse comes in:
float.Parse accepts a string and if possible, returns a float value.
Almost every type contains the Parse method which is used to transform a string into the calling one.

How to extract console output into variable between two points?

I would like to extract the section of console output that occurs between two specific points in a program and store that into a variable. This would be executed in a loop many times. There is no need for output to be echoed into the regular console (if that makes things more efficient).
i.e.
foreach (Procedure p in procedures) {
BeginCapturingConsoleOutput();
p.Execute();
string procedureOutput = EndCapturingConsoleOutput();
}
The code on this page in MSDN does what I think you are looking for:
http://msdn.microsoft.com/en-us/library/16f09842.aspx
Basically, it sets the output stream to something that you define (in the case of the example, a file), performs some action, and at the end sets it back to the standard output stream.

C# - Suggestions of control statement needed

I'm a student and I got a homework i need some minor help with =)
Here is my task:
Write an application that prompts the user to enter the size of a square and display a square of asterisks with the sides equal with entered integer. Your application works for side’s size from 2 to 16. If the user enters a number less than 2 or greater then 16, your application should display a square of size 2 or 16, respectively, and an error message.
This is how far I've come:
start:
int x;
string input;
Console.Write("Enter a number between 2-16: ");
input = Console.ReadLine();
x = Int32.Parse(input);
Console.WriteLine("\n");
if (x <= 16 & x >= 2)
{
control statement
code
code
code
}
else
{
Console.WriteLine("You must enter a number between 2 and 16");
goto start;
}
I need help with...
... what control statment(if, for, while, do-while, case, boolean) to use inside the "if" control.
My ideas are like...
do I write a code that writes out the boxes for every type of number entered? That's a lot of code...
..there must be a code containing some "variable++" that could do the task for me, but then what control statement suits the task best?
But if I use a "variable++" how am I supposed to write the spaces in the output, because after all, it has to be a SQUARE?!?! =)
I'd love some suggestions on what type of statements to use, or maybe just a hint, of course not the whole solution as I am a student!
It's not the answer you're looking for, but I do have a few suggestions for clean code:
Your use of Int32.Parse is a potential exception that can crash the application. Look into Int32.TryParse (or just int.TryParse, which I personally think looks cleaner) instead. You'll pass it what it's parsing and an "out" parameter of the variable into which the value should be placed (in this case, x).
Try not to declare your variables until you actually use them. Getting into the habit of declaring them all up front (especially without instantiated values) can later lead to difficult to follow code. For my first suggestions, x will need to be declared ahead of time (look into default in C# for default instantiation... it's, well, by default, but it's good information to understand), but the string doesn't need to be.
Try to avoid using goto when programming :) For this code, it would be better to break out the code which handles the value and returns what needs to be drawn into a separate method and have the main method just sit around and wait for input. Watch for hard infinite loops, though.
It's never too early to write clean and maintainable code, even if it's just for a homework assignment that will never need to be maintained :)
You do not have to write code for every type of number entered. Instead, you have to use loops (for keyword).
Probably I must stop here and let you do the work, but I would just give a hint: you may want to do it with two loops, one embedded in another.
I have also noted some things I want to comment in your code:
Int32.Parse: do not use Int32, but int. It will not change the meaning of your code. I will not explain why you must use int instead: it is quite difficult to explain, and you would understand it later for sure.
Avoid using goto statement, except if you were told to use it in the current case by your teacher.
Console.WriteLine("\n");: avoid "\n". It is platform dependent (here, Linux/Unix; on Windows it's "\r\n", and on MacOS - "\n\r"). Use Environment.NewLine instead.
x <= 16 & x >= 2: why & and not ||?
You can write string input = Console.ReadLine(); instead of string input; followed by input = Console.ReadLine();.
Since it's homework, we can't give you the answer. But here are some hints (assuming solid *'s, not white space in-between):
You're going to want to iterate from 1 to N. See for (int...
There's a String constructor that will allow you to avoid the second loop. Look at all of the various constructors.
Your current error checking does not meet the specifications. Read the spec again.
You're going to throw an exception if somebody enters a non-parsable integer.
goto's went out of style before bell-bottoms. You actually don't need any outer control for the spec you were given, because it's "one shot and go". Normally, you would write a simple console app like this to look for a special value (e.g., -1) and exit when you see that value. In that case you would use while (!<end of input>) as the outer control flow.
If x is greater or equal to 16, why not assign 16 to it (since you'll eventually need to draw a square with a side of length 16) (and add an appropriate message)?
the control statement is:
for (int i = 0; i < x; i++)
{
for ( int j = 0; j < x; j++ )
{
Console.Write("*");
}
Console.WriteLine();
}
This should print a X by X square of asterisks!
I'ma teacher and I left the same task to my students a while ago, I hope you're not one of them! :)

Find the x, y point of a string within a text box

Is there a way to return a point for a string within a text box? I found a COM function GetTextExtentPoint that will return the length of a string, but I want to know the point where the string starts.
You're looking for the GetPositionFromCharIndex method.
First, figure out the index of the first character of the string.
int index = textBox1.Text.IndexOf(someString);
Then use GetPositionFromCharIndex.
Point stringPos = textBox1.GetPositionFromCharIndex(index);
(Code not tested, but something like this should work. Of course you will have to deal with the possibility of duplicate occurrences of your string in the textbox.)
what comes to mi mind is to take a snapshot of both the form and text then do some fancy image comparing to find the starting point.. but for this you need to write/download a library that has theese comparing methods... thus becoming very complicated...
why do you need to do this?

Categories