Text file only reading odd OR even lines? - c#

I'm trying to write a little C# program that reads from a text file and lets you choose a line to print out.
For some reason, it will only print lines 1,3,5,etc.
If I change the bit that says int chooseLine = Convert.ToInt32(input); to int chooseLine = (int)Convert.ToInt64(input);, then it only prints even lines.(0,2,4,6,etc).
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
class Steve
{
public static int count = 0;
public static String[] steveTalk;
public static void Main()
{
using (StreamReader r = new StreamReader("Steve.txt"))
{
string line;
while ((line = r.ReadLine()) != null)
{
count++;
}
}
using (StreamReader sr = new StreamReader("Steve.txt"))
{
int i = 0;
steveTalk = new String[count];
String line;
while ((line = sr.ReadLine()) != null)
{
steveTalk[i] = line;
Console.WriteLine(steveTalk[i]);
i++;
}
}
while (true)
{
string input = Console.ReadLine();
int chooseLine = Convert.ToInt32(input);
try
{
Console.WriteLine(steveTalk[chooseLine]);
}
catch
{
Console.WriteLine("Error! Not a number or array index out of bounds");
}
Console.ReadLine();
}
}
}
Any ideas?

I'd like to suggest the System.IO.File.ReadAllLines(filename) method.
string []lines=System.IO.File.ReadAllLines("Steve.txt");
string input ;
while ((input = Console.ReadLine()) != "end")
{
int chooseLine;
int.TryParse(input,out chooseLine);
if(chooseLine<lines.Length)
{
Console.WriteLine(lines[chooseLine]);
}
}

There is no such problem with your code. What you might experience is that you have a Console.ReadLine() at the end of your loop, so if you enter a number it will show that line, then enter another number, that number will be ignored. Every other number that you enter will be ignored, which fits your description if you only tried to enter the numbers in sequence.
Here is some improvements to the code.
Use File.ReadAlLines to read the file.
Don't use exceptions unless you need it. You can easily check the input before any exception occurs.
Code:
using System;
using System.IO;
class Steve {
public static void Main() {
string[] lines = File.ReadAllLines("Steve.txt");
while (true) {
int line;
if (Int32.TryParse(Console.ReadLine(), out line)) {
if (line >= 0 && line < lines.Length) {
Console.WriteLine(lines[chooseLine]);
} else {
Console.WriteLine("Error! Array index out of bounds");
}
} else {
Console.WriteLine("Error! Not a number");
}
}
}
}

Related

How to read C# . using StreamReader

I'm trying to read a string with StreamReader, so I don't know how to read it.
using System;
using System.Diagnostics;
using System.IO;
using System.Text;
namespace
{
class Program
{
static void Main(string[] args)
{
string itemCostsInput = "25.34\n10.99\n250.22\n21.87\n50.24\n15";
string payerCountInput = "8\n";
string individualCostInput = "52.24\n";
double individualCost = RestaurantBillCalculator.CalculateIndividualCost(reader2, totalCost);
Debug.Assert(individualCost == 54.14);
uint payerCount = RestaurantBillCalculator.CalculatePayerCount(reader3, totalCost);
Debug.Assert(payerCount == 9);
}
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace as
{
public static class RestaurantBillCalculator
{
public static double CalculateTotalCost(StreamReader input)
{
// I want to read the input (not System.IO.StreamReader,
25.34
10.99
250.22
21.87
50.24
15
//below is what i tried..
int[] numbers = new int[6];
for (int i = 0; i < 5; i++)
{
numbers[int.Parse(input.ReadLine())]++;
}
for (int i = 0; i < 5; i++)
{
Console.WriteLine(numbers[i]);
}
return 0;
}
public static double CalculateIndividualCost(StreamReader input, double totalCost)
{
return 0;
}
public static uint CalculatePayerCount(StreamReader input, double totalCost)
{
return 0;
}
}
}
Even when I googled it, only file input/output came up with that phrase.
I want to get a simple string and read it.
int[] numbers = new int[6]; // The number at the index number
// take the given numbers
for (int i = 0; i < n; i++)
{
numbers[int. Parse(sr. ReadLine())]++;
}
I tried the above method, but it didn't work.
I just want to get the index and read the contents of itemCostsInput as it is. If I just execute Console.writeLine, String == System.IO.StreamReader
comes out I want to read and save the values of itemCostsInput respectively. I just want to do something like read.
I'm sorry I'm not good at English
I expected input Read
25.34
10.99
250.22
21.87
50.24
15
but console print System.IO.StreamReader
This lines are the ones causing (more) trouble I think:
for (int i = 0; i < 5; i++)
{
numbers[int.Parse(input.ReadLine())]++;
}
Should be
for (int i = 0; i < 5; i++)
{
numbers[i] = int.Parse(input.ReadLine());
}
But since you have a decimal input (in string format due to the streamreader), maybe numbers should be an array of decimals.
Also there are quite a few remarks about the use of StreamReader, since if the file doesn't have 5 or more lines, your program will also break. I let this here hoping will clarify something to you, though
Your code does not make sense in its current state.
Please read up on Streams.
Usually you'd get a stream from a file or from a network connection but not from a string.
You are confusing integer and double.
The double data type represents floating point numbers.
It seems to me that you just started programming and are missing out on most of the fundamentals.
First, convert your string input into a stream:
static System.IO.Stream GetStream(string input)
{
Stream stream = new MemoryStream();
StreamWriter writer = new StreamWriter(stream);
writer.Write(input);
writer.Flush();
stream.Position = 0;
return stream;
}
Now you can convert your input to a stream like this:
// ... code ...
string itemCostsInput = "25.34\n10.99\n250.22\n21.87\n50.24\n15";
var dataStream = GetStream(itemCostsInput);
// ... code ...
Now you that you converted your string input into a stream you can start to parse your data and extract the numbers:
static List<double> GetDoubleFromStream(Stream stream)
{
if (stream == null) {
return new List<double>();
}
const char NEWLINE = '\n';
List<double> result = new List<double>();
using (var reader = new StreamReader(stream))
{
// Continue until end of stream has been reached.
while (reader.Peek() > -1)
{
string temp = string.Empty;
// Read while not end of stream and char is not new line.
while (reader.Peek() != NEWLINE && reader.Peek() > -1) {
temp += (char)reader.Read();
}
// Perform another read operation
// to skip the current new line character
// and continue reading.
reader.Read();
// Parse data to double if valid.
if (!(string.IsNullOrEmpty(temp)))
{
double d;
// Allow decimal points and ignore culture.
if (double.TryParse(
temp,
NumberStyles.AllowDecimalPoint,
CultureInfo.InvariantCulture,
out d))
{
result.Add(d);
}
}
}
}
return result;
}
This would be your intermediate result:
Now you can convert your input to a stream like this:
// ... code ...
string itemCostsInput = "25.34\n10.99\n250.22\n21.87\n50.24\n15";
var dataStream = GetStream(itemCostsInput);
var result = GetDoubleFromStream(dataStream);
// ... code ...

my Distinct function is not working and i can't see why c#

The Distinct function is not working when it should. This is the input I am using:
one one two
Distinct
End
this is my whole code:
using System;
using System.Collections.Generic;
using System.Linq;
namespace Array.Processing
{
class Program
{
static void Main(string[] args)
{
string input = Console.ReadLine();
List<string> texts = input.Split(" ").ToList();
string text = Console.ReadLine();
int a = 0;
while (text != "END")
{
text = Console.ReadLine();
List<string> infos = text.Split(" ").ToList();
if (text == "Distinct")
{
texts = texts.Distinct().ToList();
}
if (text == "Reverse")
{
texts.Reverse();
}
if (infos[0] == "Replace")
{
if (texts.Count > int.Parse(infos[1]) && int.Parse(infos[1]) >= 0)
{
texts.RemoveAt(int.Parse(infos[1]));
texts.Insert(int.Parse(infos[1]), infos[2]);
}
else
{
a++;
}
}
}
for(int n = 0; n < a; n++)
{
Console.WriteLine("Invalid input!");
}
foreach (string info in texts)
{
Console.Write(info + " ");
}
}
}
}
and this is the output I am receiving:
one one two
I can't figure out why both "one" remains. Been looking at the code for over an hour so far and still nothing...
First you have
string input = Console.ReadLine(); // one one two
Next you have
string text = Console.ReadLine(); // Distinct
Next, first time inside the while you have
text = Console.ReadLine(); // End
At this point you check if (text == "Distinct") but by now its been overwritten to "End" so you never end up calling Distinct() on the list.

Extract decimal/ integer values before a character sequence in C#

I want to extract all decimal/ integer value before a character sequence(am/AM) until an alphabet or a special charecter comes up value
Input Output
PEK\n2545 AMAzerbhaijan 2545
PEK\n2545 AMamorphous 2545
ANGwwquui\3.0 amAm 3.0
Awyu&&#^/Non-Prog//#*(*889/328.19 am -> 328.19
qii2781a/k28U28am 28
PEK\nam2545 AM 2545
Can I know what is the best possible way to do this? Thanks in advance.
Given the examples you showed, I believe this would do the trick:
public string ParseData(string input)
{
StringBuilder numberBuilder = new StringBuilder();
string terminatorChars = "am";
bool isCaseSensitive = false;
int terminatorCharLength = terminatorChars.Length;
for (int i = 0; i < input.Length; i++)
{
if (input.Length - i >= terminatorCharLength)
{
var currentSubstr = input.Substring(i, terminatorCharLength);
if ((currentSubstr == terminatorChars) || (!isCaseSensitive && currentSubstr.ToLowerInvariant() == terminatorChars.ToLowerInvariant()))
if(numberBuilder.Length>0)
return numberBuilder.ToString();
}
if (Char.IsDigit(input[i]) || input[i] == '.')
numberBuilder.Append(input[i]);
else if (Char.IsWhiteSpace(input[i]))
continue;
else
numberBuilder.Clear();
}
return null;
}
The data is fixed width data with name the first 50 character and value the data after column 50. See code below
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace ConsoleApplication1
{
class Program
{
const string FILENAME = #"c:\temp\test.txt";
static void Main(string[] args)
{
StreamReader reader = new StreamReader(FILENAME);
string line = "";
List<KeyValuePair<string, decimal>> data = new List<KeyValuePair<string,decimal>>();
int lineNumber = 0;
while((line = reader.ReadLine()) != null)
{
if(++lineNumber > 1)
{
string key = line.Substring(0, 50).Trim();
decimal value = decimal.Parse(line.Substring(50));
data.Add(new KeyValuePair<string,decimal>(key,value));
}
}
}
}
}

Use a while loop to read in the entire text file and output a message a list with only the even numbers from the file to the screen

I can't figure out how to output a message a list with only the even numbers from the file to the screen.
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace EvenNumbersFile
{
class Program
{
static void Main(string[] args)
{
StreamReader myReader = new StreamReader("NumbersFile.txt");
string line = "";
while (line != null)
{
line = myReader.ReadLine();
if (line != null)
Console.WriteLine(line);
}
myReader.Close();
Console.ReadLine();
}
}
}
I think I understand what you want now. You need to parse the number in the file then check to see if it is evenly divisible by two. Here is some code to try:
while (line != null)
{
line = myReader.ReadLine();
if (line != null)
{
int temp;
if (int.TryParse(line, out temp) && (temp % 2 == 0))
{
Console.WriteLine(line);
}
}
}
Something like this sounds like what you need:
while (line != null)
{
line = myReader.ReadLine();
int number = -1;
if (line != null)
{
if (Int32.TryParse(line, out number))
{
if (number % 2 == 0)
{
Console.WriteLine(number);
}
}
}
}
The .TryParse can be omitted if you can guarantee that the input file will only contain numbers.
More complete version:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PrintEvenNumbers
{
class Program
{
static void Main(string[] args)
{
Console.Clear();
SafeForWork();
Console.WriteLine();
JustShowingOff();
Console.ReadLine();
}
private static void SafeForWork()
{
StreamReader myReader = new StreamReader(#"C:\Users\Public\NumbersFile.txt");
string line = "";
while (line != null)
{
line = myReader.ReadLine();
int number = -1;
if (Int32.TryParse(line, out number))
{
if (number % 2 == 0)
{
Console.WriteLine(number);
}
}
}
myReader.Close();
}
private static void JustShowingOff()
{
List<String> Contents = File.ReadAllLines(#"C:\Users\Public\NumbersFile.txt").ToList();
List<String> Evens = Contents.Where(var => (Int32.Parse(var)) % 2 == 0).ToList();
Evens.ForEach(var => Console.WriteLine(var));
}
}
}
File contents:
1
2
4
13
6
99
8

How do I read and separate the first portion of the array from the rest?

So I have a minor problem with my code and am almost certain that it should be an easy fix. So I have some data that I have in a file that reads:
25 150
60
63
61
70
72
68
66
68
70
The problem with this bit of data is that the first line: "25 150", are suppose to be saved as integers so that I can use them throughout the code. I have the problem solved without that line of numbers because the array can separate them as it normally does. How do I write the code so that it separates those two numbers and saves them as two different integers? This is the code I have so far:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace proj11LEA
{
class Program
{
const int SIZE = 50;
static void Main(string[] args)
{
int[] volts = new int[SIZE];
string environment = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal) + "\\";
Console.WriteLine("\nResistor Batch Test Analysis Program\n");
Console.WriteLine("Data file must be in your Documents folder.");
Console.WriteLine("Please enter the file name: ");
string input = Console.ReadLine();
string path = environment + input;
StreamReader data = new StreamReader(path);
string fromFile;
int count = 0;
int start = 1;
Console.WriteLine("\nRes#\tDissipation\tPassed");
do
{
fromFile = data.ReadLine();
if (fromFile != null)
{
string[] dataArray = fromFile.Split();
volts[count] = int.Parse(dataArray[0]);
count++;
}
} while (fromFile != null);
for (int i = 0; i < count; i++ )
{
int diss = (volts[i] * volts[i])/25;
if (diss >= 150)
{
string answer = ("yes");
Console.WriteLine("{0}\t{1:d2}\t\t{2}", start++, diss , answer);
}
else
{
string answer = ("no");
Console.WriteLine("{0}\t{1:d2}\t\t{2}", start++, diss, answer);
}
}
Console.ReadLine();
}
}
}
this will create a list of int from a text file of numbers like you have, then you can manipulate it how you need!
List<int> data = new List<int>();
using (StreamReader xReader = new StreamReader("TextFile1.txt"))
{
string line;
while (!xReader.EndOfStream)
{
line = xReader.ReadLine();
string[] input = line.Split(' ', '\r');// this splits the line on the space and newline
foreach (string item in input)
{
data.Add(Convert.ToInt32(item));
}
}
}

Categories