Console.Read() until eof [closed] - c#

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I have to read integers from console sepetating with white characters until end of file, but I don't know how, I search for the answer but I couldn't find it.
while((x = Console.Read()) != null)

Note that the method does not return -1 unless you perform one of the
following actions:
Simultaneously press the Control modifier key and Z console key (Ctrl+Z), which signals the end-of-file condition.
Press an equivalent key that signals the end-of-file condition, such as the F6 function key in Windows.
Redirect the input stream to a source, such as a text file, that has an actual end-of-file character.
MSDN Read() method.
Then you can read file by character and calculate each separated value with simple math. It's lazy then will not iterate file to the end immediately for calculating all values.
static void Main(string[] args)
{
foreach (int i in Read(Console.In))
{
Console.WriteLine(i);
}
}
static IEnumerable<int> Read(TextReader rdr)
{
int ch;
bool neg = false;
int value = 0;
int count = 0;
while ((ch = rdr.Read()) != -1)
{
if (char.IsWhiteSpace(ch))
{
if (count > 0)
yield return neg ? -value : value;
count = 0;
value = 0;
neg = false;
}
else if (count == 0 && ch == '-')
{
neg = true;
}
else if (ch >= '0' && ch <= '9')
{
count++;
value = value*10 + (ch - '0');
}
else
throw new InvalidDataException();
}
if (count > 0)
yield return neg ? -value : value;
}

int values are not nullable. You have to use negative one.
while((x = Console.Read()) != -1)

Related

C# 2 List doesn't match [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed last month.
Improve this question
List<Object> rollerliste = (from row in roller.AsEnumerable() select (row["rolName"])).ToList();
List<Object> yetkiliste = (from row in roller.AsEnumerable() select (row["Visible"])).ToList();
for(int r = 0; r < rollerliste.Count(); r++)
{
for (int y = 0; y < yetkiliste.Count(); y++)
{
if(rollerliste[r].ToString() == "frmMasalar" && yetkiliste[y].ToString() == "true" && r == y)
{
cu.frmMasalar = 1;
}
else
{
cu.frmMasalar = 0;
}
}
}
Actually
if(rollerliste[r].ToString() == "frmMasalar" && yetkiliste[y].ToString() == "true" && r == y)
it seems to be checking for correct data but not working.
rollerliste
yetkiliste
frmMasalar
True
frmYonetim
True
I just want to make check rollerliste if column1 is true "button.Enable = true" or false
Please note that, within your loops, you are overwriting cu.frmMasalar over and over again. That alone might be the reason you're not getting what you want.
I'm not sure I totally understand what you want to do. But, check whether this might be simpler:
cu.frmMasalar = 0;
foreach(var row in roller.AsEnumerable()) {
if((string) row["rolName"] == "frmMasalar" && (bool) row["Visible"]) {
cu.frmMasalar = 1;
break;
}
}
There are also more condensed ways to do this, if the point is to find the one entry where rolName == "frmMasalar":
cu.frmMasalar = 0;
var matchingRow = roller.AsEnumerable()
.FirstOrDefault(r => (string) r["rolName"] == "frmMasalar"
&& (bool) row["Visible"]);
if(matchingRow != null)
cu.frmMasalar = 1;

Why is List<T>.Add method not working in the specific if/else block? (C#) [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
I have an Infint class with one List field. In the main program, I want to read numbers (character by character) and add them to this list.
The assignment itself doesn't matter in this moment, what I'm wondering is why I can't add values to the list of the Infint object from the if/else block (inside the first while loop). I have initialised the List itself in the class constructor. I added the line number1.Number.Add(1) for debugging reasons, since the code wasn't working and I've come to realize it seems to be working fine outside that if/else block. I can't seem to find the solution.
Here are the following implementations:
internal class Infint
{
public bool isNegative { get; set; }
public List<int> Number { get; set; }
public Infint()
{
isNegative = false;
Number = new List<int>();
}
}
static void Main(string[] args)
{
using (StreamReader sr = new StreamReader("infint.txt"))
{
int i;
char num;
for (int operation = 0; operation < 3; operation++)
{
Infint number1 = new Infint();
Infint number2 = new Infint();
number1.Number.Add(1); //works
i = sr.Read();
while (sr.Peek() >= 0)
{
number1.Number.Add(1); //works
if (i == 10 || i == 13)
break;
num = (char)i;
if (operation == 0)
{
number1.Number.Add(1); //doesn't work
if (i == 45)
number1.isNegative = true;
else
{
number1.Number.Add(1); //doesn't work
//number1.Number.Add((int)Char.GetNumericValue(num));
}
}else if(operation == 1)
{
if (i == 45)
number2.isNegative = true;
else
{
number2.Number.Add((int)Char.GetNumericValue(num));
}
}else if(operation == 2)
{
Console.WriteLine("counts of num1: " + number1.Number.Count);
for (var k = 0; k < number1.Number.Count; k++)
{
Console.Write(number1.Number[k]);
}
Console.WriteLine("counts of num2: " + number2.Number.Count);
for (var k = 0; k < number2.Number.Count; k++)
{
Console.Write(number2.Number[k]);
}
}
i = sr.Read();
}
if (i == -1)
{
break;
}
//i = sr.Read();
}
}
Console.Read();
}
Removing the various noise in your code (it's extremely low quality, if you care), what you're left with is:
using var sr = new StreamReader("infint.txt");
for (int operation = 0; operation < 3; operation++)
{
var i = sr.Read();
while (sr.Peek() >= 0)
{
if (i == 10 || i == 13) break;
if (operation == 0)
{
// oh noes
}
}
}
So looking at the code and assuming what you describe is correct (if vague), that means that your text file starts with a new line, possibly two (you don't even mention your OS, let alone the contents of the file). If that is indeed the case, then it should be strikingly obvious why operation can't be 0 around the branch you're expecting it to be.

How to pause a for loop until the enter key is pressed? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
for example
bool x = false;
if(press enter)
{
x = true;
}
for(int i = 0; i < 10; i++)
{
if(x == true)
print (i);
x = false;
}
code like that always give me 0 after enter pressed instead of the whole sequence 1,2,3...10.
I found three answer online, but all of them are not wrote in c#, I actually use it in Unity, so it has to be c#..
for(int i = 0; i < 10; i++)
{
if(x == true)
print(i);
// This line is executed allways
x = false;
}
So what happens is that
in the first call x == true so it prints 0.
Then it sets x = false
In future iteration x == false => so no more output.
You probably wanted something like
// only check this once since it isn't changed in the loop
// do not loop at all if button wasn't pressed
if(x)
{
// Do all prints in a loop
for(int i = 0; i < 10; i++)
{
print(i); // prints 0 1 2 3 4 5 6 7 8 9
}
// reset the flag so you do the printing only in the frame
// where the button was pressed
x = false;
}
And for Unity specific you might want to use Input.GetKeyDown instead of x.
You can run your for loop during the frame that the return key is released. This ensures that we don't run this for every frame that the key is down (I'm assuming you don't want that). To do this we just check with Input.GetKeyUp which returns a boolean when the specified key is released.
if(Input.GetKeyUp(KeyCode.Return))
{
for(int i = 0; i < 10; i++)
print(i);
}
You can use Coroutine with Input.GetKeyDown and then do yield return.
For Example:
private bool _pause = false;
private void Start()
{
StartCoroutine(FuncName());
}
private void Update()
{
if (Input.GetKeyDown(KeyCode.Return))
{
_pause = !_pause;
}
}
private IEnumerator FuncName()
{
for(int i = 0; i < 10; i++)
{
while (_pause)
{
yield return null;
print (i);
}
}
}

Check if a String contains something between quotes

I am writing I application where the user can input a document. Then I read each line of the Document and work further with the attributes.
In Each line we have 5 attributes. The Attributes get separated by a semicolon.
For Example:
If a Attribute have a semicolo in his name the user will input the attribute then so in the Document:
"test;with"
Now I want to check if the attribute is in quotes and ignore it. How would you guys do it?
Here is the important code snippet:
foreach (string line in lines)
{
if (line == "")
{
continue;
}
if (lineindex > lines.Length)
{
continue;
}
lineindex++;
string[] words = line.Split(';'); // i would add here a if statement
foreach (string word in words)
{
count++;
if (count == 6)
{
attribNewValue = "";
maskName = "";
actualAttrbValue = "";
actualAttrbName = "";
attribNameForEdit = "";
count = 1;
maskexist = false;
attribexist = false;
}
else
{
// Or here to each word
if (count == 1)
{
maskName = word;
}
else if (count == 2)
{
actualAttrbName = word;
}
else if (count == 3)
{
actualAttrbValue = word;
}
else if (count == 4)
{
attribNameForEdit = word;
}
else if (count == 5)
{
attribNewValue = word;
}
}
Thank you in advance!
You can use String.IndexOf(char value) and String.LastIndexOf(char value) to determine this:
string[] words;
int semicolonIndex = line.IndexOf(';');
int firstQuoteIndex = line.IndexOf('"');
int lastQuoteIndex = line.LastIndexOf('"');
if (firstQuoteIndex == lastQuoteIndex)
continue;
if (semicolonIndex > firstQuoteIndex && semicolonIndex < lastQuoteIndex)
words = line.Split(';');
More information:
IndexOf(): https://msdn.microsoft.com/en-us/library/system.string.indexof(v=vs.110).aspx
LastIndexOf(): https://msdn.microsoft.com/en-us/library/system.string.lastindexof(v=vs.110).aspx
As one of the comments mentioned, this can also be achieved with regular expressions in far fewer lines of code than my solution, but gauging your skill level (no offense) I think this is easier for you to read, understand, and get started with. Regardless of whether or not there is a more elegant solution, string manipulation is a pretty basic things and it would be good to familiarize yourself with all of the methods on the String class as found here: https://msdn.microsoft.com/en-us/library/system.string_methods(v=vs.110).aspx
Lastly, while this is purely developer-preference, I would recommend using String.Empty instead of "". This makes your code's intentions more explicit to other readers / developers. By using "", one might ask "Well did they MEAN to use an empty string, or did they make a typo and aren't assigning what they think they're assigning?" By using String.Empty, there is no question that you meant to use an empty string. So I would do if (line == String.Empty) continue; instead of if (line == "") continue;

How to break two for loop [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
How to break two for loop at the highlighted line. (after showing the MessageBox.Show("THE ITEM ID DOES NOT EXIST.!"); )
bool conditionitem = true;
for (int cun = 0; cun < ItemIdNumber.Length; cun++)
{
int Item_Id = Convert.ToInt32(ItemIdNumber[cun]);
for (int yyu = 0; yyu <= 1258038; yyu++)
{
int weer = c[yyu];
if (weer == Item_Id)
{
conditionitem = false;
itemseq = yyu;
}
}
if (conditionitem != false)
{
MessageBox.Show("THE ITEM ID DOES NOT EXIST.!");
break; //--> here i want two break for two times
}
}
By this break it only break the first loop.
Two options I can think of:
(1) Set a flag inside the second loop before you break out of it. Follow the inner iteration with a condition that breaks out of the first iteration if the flag is set.
bool flag = false;
foreach (item in Items)
{
foreach (item2 in Items2)
{
flag = true; // whenever you want to break
break;
}
if (flag) break;
}
(2) Use a goto statement.
foreach (item in Items)
{
foreach (item2 in Items2)
{
goto GetMeOutOfHere: // when you want to break out of both
}
}
GetMeOutOfHere:
// do what you want to do.
You can refactor the loop to be a method that finds the item:
SomeType SomeMethod(int itemId)
{
for (int cun = 0; cun < ItemIdNumber.Length; cun++)
{
int Item_Id = Convert.ToInt32(ItemIdNumber[cun]);
for (int yyu = 0; yyu <= 1258038; yyu++)
{
if (c[yyu] == itemId) return yyu;
}
}
return null;
}
Then just use that:
var item = SomeMethod(Item_Id);
if(item == null)
{
MessageBox.Show("THE ITEM ID DOES NOT EXIST.!");
}
else
{
// ...
}
This also avoids mixing UI logic and internal logic.
Put your nested loop into a function and return true/false whenever you want to break the loop?
bool Function()
{
for(int i = 0; i < 10; ++i)
{
for(int j = 0; j < 10; ++j)
{
if (error)
{
MessageBox.Show("THE ITEM ID DOES NOT EXIST.!");
return false;
}
}
}
return true;
}

Categories

Resources