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 ...
Related
I need to take a number from every line of a text file and find the average. I'm using stream reader to take the number out of a text file, I don't know where to go from here. Here's what I've done so far
using (StreamReader sr = new StreamReader("pupilSkiTimes.txt"))
{
string line = "";
while ((line = sr.ReadLine()) != null)
{
string[] components = line.Split("~".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
skiTime.Add(components[7]);
}
sr.Close();
}
How do I get this to read from every line of the text file, and once that's done, how do I get the average.
In case you need to know, the data I'm trying to read is doubles, e.g "23.43"
Here is how I will do it, as you mentioned in comments components[7] are double data that you read from the file.
We need to parse it to double, sum it up and divide it by the counting time we are able to parse the number in the file. If the number is not parsed and you want the total average of all lines then move the count out of the if statement.
using (StreamReader sr = new StreamReader("pupilSkiTimes.txt"))
{
string line;
double sum = 0;
int count = 0;
while ((line = sr.ReadLine()) != null)
{
string[] components = line.Split("~".ToCharArray(),
StringSplitOptions.RemoveEmptyEntries);
if (double.TryParse(components[7], out var result))
{
count++;
sum += result;
}
}
sr.Close();
var average = sum / count;
Console.WriteLine(average);
}
I think the handy method for this situation like this is useful hopefully you use it, I am using a similar this in my codes.
I am passing FilePath, Separator, and index value
static double getAvgAtIndex(string fPath, char seperator, int index)
{
double sum = 0;
int counter = 0;
using (StreamReader sr = new StreamReader(fPath))
{
string line = "";
while ((line = sr.ReadLine()) != null)
{
double rawData = 0;
string[] lineData = line.Split(seperator, StringSplitOptions.RemoveEmptyEntries);
double.TryParse(lineData[index], out rawData);
sum += rawData;
counter++;
}
sr.Close();
}
return sum / counter;
}
Usage of this,
static void Main(string[] args)
{
Console.WriteLine("The Avg is: {0}", getAvgAtIndex(#"..\myTextFile.txt", '~' ,1));
// The Avg is: 34.688
}
Here is how to use LINQ to clean up the code a bit
static class Program
{
static void Main(string[] args)
{
var data = File.ReadAllLines("pupilSkiTimes.txt")
.Select((line)=> line.Split("~".ToCharArray(), StringSplitOptions.RemoveEmptyEntries));
List<double> skiTime = new List<double>();
foreach (var parts in data)
{
if (double.TryParse(parts[7], out double x))
{
skiTime.Add(x);
}
}
double average = skiTime.Average();
}
}
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));
}
}
}
}
}
I need to design a program that reads in an ASCII text file and creates an output file that contains each unique ASCII character and the number of times it appears in the file. Each unique character in the file must be represented by a character frequency class instance. The character frequency objects must be stored in an array list. My code is below:
using System.IO;
using System;
using System.Collections;
namespace ASCII
{
class CharacterFrequency
{
char ch;
int frequency;
public char getCharacter()
{
return ch;
}
public void setCharacter(char ch)
{
this.ch = ch;
}
public int getfrequency()
{
return frequency;
}
public void setfrequency(int frequency)
{
this.frequency = frequency;
}
static void Main()
{
string OutputFileName;
string InputFileName;
Console.WriteLine("Enter the file path");
InputFileName = Console.ReadLine();
Console.WriteLine("Enter the outputfile name");
OutputFileName = Console.ReadLine();
StreamWriter streamWriter = new StreamWriter(OutputFileName);
string data = File.ReadAllText(InputFileName);
ArrayList al = new ArrayList();
//create two for loops to traverse through the arraylist and compare
for (int i = 0; i < data.Length; i++)
{
int k = 0;
int f = 0;
for (int j = 0; j < data.Length; j++)
{
if (data[i].Equals(data[j]))
{
f++;
if (i > j) { k++; }
}
}
al.Add(data[i] + "(" + (int)data[i] + ")" + f + " ");
foreach (var item in al)
{
streamWriter.WriteLine(item);
}
}
streamWriter.Close();
}
}
}
When I run the program, the program does not stop running and the output file keeps getting larger until it eventually runs out memory and I get an error stating that. I am not seeing where the error is or why the loop won't terminate. It should just count the characters but it seems to keep looping and repeating counting the characters. Any help?
Try this approach :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace yourNamespace
{
class Char_frrequency
{
Dictionary<Char, int> countMap = new Dictionary<char, int>();
public String getStringWithUniqueCharacters(String input)
{
List<Char> uniqueList = new List<Char>();
foreach (Char x in input)
{
if (countMap.ContainsKey(x))
{
countMap[x]++;
}
else
{
countMap.Add(x, 1);
}
if (!uniqueList.Contains(x))
{
uniqueList.Add(x);
}
}
Char[] uniqueArray = uniqueList.ToArray();
return new String(uniqueArray);
}
public int getFrequency(Char x)
{
return countMap[x];
}
}
}
This might not be the ideal solution. But you can use these methods
I did this code, but it doesnt give summary. Still I can get numbers of each row, but not summary...
using System;
using System.IO;
namespace Progaram
{
class Count
{
static void Main()
{
using (StreamReader sr = new StreamReader("file.txt"))
{
string[] numbers = File.ReadAllLines("file.txt");
int summary = 0;
for (int i = 0; i < numbers.Length; i++)
{
summary += numbers[i];
//Console.WriteLine(numbers[i]);
}
Console.WriteLine(summary);
sr.ReadLine();
}
}
}
}
Your current solution will not compile.
You'll receive the following compilation error:
Cannot convert type 'string' to 'int'.
You'll want to convert the parsed string into an int.
Also, you're using a StreamReader, and reading a single line after reading in all lines. You don't need the StreamReader in this case.
using System;
using System.IO;
namespace Progaram
{
class Count
{
static void Main()
{
string[] numbers = File.ReadAllLines("file.txt");
int summary = 0;
for (int i = 0; i < numbers.Length; i++)
{
summary += Convert.ToInt32(numbers[i]);
}
Console.WriteLine(summary);
}
}
}
You can't add a string to an int.
You need to either convert the entire string array to an int array with
int[] intNumbers = Array.ConvertAll(numbers, int.Parse);
Then index this array instead
summary += intNumbers[i];
Or as Michael suggests, convert numbers[i] before adding
summary += int.Parse(numbers[i]);
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");
}
}
}
}