I keep getting the aggravated CS0165 error code. I have re-written this several times and even googled the issues. I cannot resolve this, it is for a college assignment that is now 2 days late. Can anyone please help. Would appreciate. This is the code below:
using System;
using System.IO;
//using System.Collections.Generic;
//using System.Linq;
//using System.Text;
//using System.Threading.Tasks;
namespace Assignment_2
{
class Program
{
static void Main()
{
string InputPath = #"C:\Users\....\Desktop\CP Class\Assignment 2\Asgn2InputFile.txt";
string OutputPath = #"C:\Users\....\Desktop\CP Class\Assignment 2\Payroll.txt";
using (StreamReader sr = new StreamReader(InputPath))
using (StreamWriter sw = new StreamWriter(OutputPath))
{
// input line
string InputLine;
// input fields
string First;
string Last;
int Hours;
int OverT;
double Pay;
// output fields
double Earnings;
double Gross;
//
sw.Write("NAME".PadRight(11));
sw.Write("HOURS WORKED ".PadRight(23));
sw.Write("PAY RATE".PadRight(20));
sw.Write("OVERTIME".PadRight(27));
sw.WriteLine();
while ((InputLine = sr.ReadLine()) != null)
// parse input line
First = InputLine.Substring(0, 5);
Last = InputLine.Substring(0, 11);
Pay = double.Parse(InputLine.Substring(31, 5));
Hours = int.Parse(InputLine.Substring(16, 2));
OverT = int.Parse(InputLine.Substring(29, 1));
//
Earnings = (Hours * Pay);
Gross = Earnings + (OverT * (Pay * 1.5));
sw.Write(First.PadRight(11)); [[ Error Code occurs here ]]
sw.WriteLine(Last.PadRight(11));
//
sw.Write(Earnings.ToString().PadLeft(10) + " # " + Gross.ToString("C").PadRight(9));
sw.WriteLine(Earnings.ToString("C").PadLeft(17));
sw.WriteLine();
//Total += Earnings;
}
}
}
}
The error CS0165 is because you are using variables that are not initialized....
the reason is the omitting of the { } here
while ((InputLine = sr.ReadLine()) != null)
which means, the while loop has as scope something else as what you need
in fact your code is equivalent to:
while ((InputLine = sr.ReadLine()) != null){
First = InputLine.Substring(0, 5);
}
leaving the rest uninitialized
Because your while loop doesn't have any braces to block the code it contains, it only takes the first line of code beneath as the content. Because the compiler cannot guarantee that line will run, the variable First might not be initialised.
So instead of doing this:
while (something)
DoSomething();
DoSomethingElse();
You should write:
while (something)
{
DoSomething();
DoSomethingElse();
}
You have multiple issues in your code
While loop braces are missing
You have declared your variables so far away from its first use and made it so long that it is difficult to see issues
Look at the below code which I think is what you want
using System;
using System.IO;
//using System.Collections.Generic;
//using System.Linq;
//using System.Text;
//using System.Threading.Tasks;
namespace Assignment_2 {
class Program {
static void Main() {
string InputPath = #"C:\Users\....\Desktop\CP Class\Assignment 2\Asgn2InputFile.txt";
string OutputPath = #"C:\Users\....\Desktop\CP Class\Assignment 2\Payroll.txt";
using (StreamReader sr = new StreamReader(InputPath))
using (StreamWriter sw = new StreamWriter(OutputPath)) {
sw.Write("NAME".PadRight(11));
sw.Write("HOURS WORKED ".PadRight(23));
sw.Write("PAY RATE".PadRight(20));
sw.Write("OVERTIME".PadRight(27));
sw.WriteLine();
// input line
string InputLine;
while ((InputLine = sr.ReadLine()) != null) {
// parse input line
var First = InputLine.Substring(0, 5);
var Last = InputLine.Substring(0, 11);
var Pay = double.Parse(InputLine.Substring(31, 5));
var Hours = int.Parse(InputLine.Substring(16, 2));
var OverT = int.Parse(InputLine.Substring(29, 1));
//
var Earnings = (Hours * Pay);
var Gross = Earnings + (OverT * (Pay * 1.5));
sw.Write(First.PadRight(11)); //Error Code occurs here
sw.WriteLine(Last.PadRight(11));
//
sw.Write(Earnings.ToString().PadLeft(10) + " # " + Gross.ToString("C").PadRight(9));
sw.WriteLine(Earnings.ToString("C").PadLeft(17));
sw.WriteLine();
//Total += Earnings;
}
}
}
}
}
Related
Application .net C#
I have problem how to get out (on button click) this (rounded red) value from lista.txt file. In a fact, that's a exchange rate list. Values are changing daily.
Mine is always on the same position.
So far, using line.substring I've got the whole column inline:
5,2599355,3058300,2770031,0057322,4095196,1123050,8419020,7941597,0027418,7470806,9262237,4796281,729514
How do I get just a bold part. Its near end of string (7,479628).
Thanks a lot.
String.Split() should be able to do what you want.
if you already have the column it would be:
var array = column.Split('\t'); //assuming the separator is a tab
In the image it looks like the lines are tab seperated?
You could read each line then perform a split using the tab character....
string[] arsplit = line.Split('\t');
and then grab the item from the array based on index which I presume you'll know
Try something like this
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace ConsoleApplication1
{
class Program
{
const string FILENAME = #"lista.txt";
static void Main(string[] args)
{
StreamReader reader = new StreamReader(FILENAME);
int lineCount = 0;
string inputline = "";
do while((inputline = reader.ReadLine()) != null)
{
if(++lineCount == 13)
{
string[] inputArray = inputline.Trim().Split(new char[] {' ','\t'},StringSplitOptions.RemoveEmptyEntries);
Console.WriteLine("Exchange Rate : '{0}'", inputArray[2]);
break;
}
}
}
}
}
I just received solution that works fine from one guy. His suggestion was to check for EUR which I'm interested for. So, after downloading file, approach is:
int counter = 0;
string line;
System.IO.StreamReader file = new System.IO.StreamReader(fullPath);
while ((line = file.ReadLine()) != null)
{
if (counter == 0)//jump first row, it's header don't need it
{
counter++;
continue;
}
if (line.Contains("EUR"))
{
line = line.Replace(" ", "");//clean spaces
line = line.Substring(3 + 3 + 3 + 8, 8);
Response.Write(line);
}
counter++;
}
file.Close();
So it maybe it can be useful for someone. In this moment I don't know which of your solutions is best. Just want to thank to all of you for help me in so short time.
I didn't get why it isn't working..
Error shows like, newArraylist (line 13); newSreamReader (line 14, 24)
does not exist.
Any help will be appreciated.
using System;
using System.IO;
using System.Collections;
namespace InsertLineInTextFile
{
class Program
{
static void Main(string[] args)
{
string strTextFileName = "file.txt";
int iInsertAtLineNumber = 2;
string strTextToInsert = "Amudha";
ArrayList lines = new ArrayList();
StreamReader rdr = new StreamReader(strTextFileName);
string line;
while ((line = rdr.ReadLine()) != null) lines.Add(line);
rdr.Close();
if (lines.Count > iInsertAtLineNumber) lines.Insert(iInsertAtLineNumber, strTextToInsert);
else
lines.Add(strTextToInsert);
StreamWriter wrtr = new StreamWriter(strTextFileName);
foreach (string strNewLine in lines) wrtr.WriteLine(strNewLine);
wrtr.Close();
}
}
}
First, you have to think over what you're going to achieve; reverse engeniering (alas!) says
insert strTextToInsert at iInsertAtLineNumber line of fileName file
(or add the text if the file is too short)
Then implementation:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
...
string fileName = "file.txt";
int iInsertAtLineNumber = 2;
string strTextToInsert = "Amudha";
List<String> lines = File
.ReadLines(fileName)
.ToList();
if (lines.Count > iInsertAtLineNumber)
lines.Insert(iInsertAtLineNumber, strTextToInsert);
else
lines.Add(strTextToInsert);
File.WriteAllLines(fileName, lines);
Please, do not use obsolete class ArrayList but List<T> (List<String> in the question). Often File.ReadLines and File.WriteAllLines are more readable and easier to maintain than StreamReader/StreamWriter.
Currently working on a project for a car park. I have a csv file which contains strings of information regarding car license plates. I have used regex already to return 90% of the license plates, however shorter personalised number plates aren;t returning correctly: ie "AA12" returns as "AA12BC" as it fits another regex.
Each string has two instances of the car license plate, is there a way to only return strings that prove correct for the regex and two instances of the number plate.
Code so far:
//start
using (TextReader reader = File.OpenText(#"C:\Users\user\documents\regdata.csv"))
{
List<string> lines = new List<string>();
string pattern = #"[A-Z]{3}[0-9]{3}";
string line;
while ((line = reader.ReadLine()) != null)
{
lines.Add(line);
}
List<string> regExs = new List<string>();
regExs.Add(#"[A-Z]{3}[0-9]{3}");
regExs.Add(#"[A-Z]{2}[0-9]{2}[A-Z]{3}");
regExs.Add(#"[A-Z]{1}[0-9]{3}[A-Z]{3}");
regExs.Add(#"[A-Z]{1}[0-9]{2}[A-Z]{3}");
regExs.Add(#"[A-Z]{1}[0-9]{1}[A-Z]{3}");
regExs.Add(#"[A-Z]{3}[0-9]{2,3}");
regExs.Add(#"[A-Z]{2}[0-9]{4}");
regExs.Add(#"[A-Z]{3}[0-9]{2}");
regExs.Add(#"[A-Z]{2}[0-9]{2}[A-Z]{3}");
using (StreamWriter writer = new StreamWriter(#"C: \Users\user\Desktop\usersNotes\plates.csv"))
{
foreach (var l in lines.Select(x => x.Split(',')[2]))
{
string result = "";
foreach (var r in regExs)
{
Regex myRegex = new Regex(r);
Match m = myRegex.Match(l);
if (m.Success)
{
result = m.Value;
break;
}
}
writer.WriteLine(l + "," + result);
}
Thanks
This should do it for you. I went ahead and coded (I think) the whole solution for you as I understand it. I made a Regex list rather than a string list; this way you don't have to build and tear down every Regex object with each loop.
Assumptions: (1) Plates never have " or , and (2) Plates don't show up more than twice.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Text;
using System.Windows.Forms;
using System.Text.RegularExpressions;
namespace DupeOnly {
public partial class Form1 : Form{
public Form1(){
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e){
string zRegData = File.ReadAllText(#"C:\Users\user\documents\regdata.csv");
HashSet<string> hsRegData = new HashSet<string>();
bool tfFirst = true;
string[] zAllPlateData = zRegData.Split(','); //License plates don't have comma's
List<Regex> rxList = new List<Regex>();
rxList.Add(new Regex(#"[A-Z]{3}[0-9]{3}"));
rxList.Add(new Regex(#"[A-Z]{2}[0-9]{2}[A-Z]{3}"));
rxList.Add(new Regex(#"[A-Z]{1}[0-9]{3}[A-Z]{3}"));
rxList.Add(new Regex(#"[A-Z]{1}[0-9]{2}[A-Z]{3}"));
rxList.Add(new Regex(#"[A-Z]{1}[0-9]{1}[A-Z]{3}"));
rxList.Add(new Regex(#"[A-Z]{3}[0-9]{2,3}"));
rxList.Add(new Regex(#"[A-Z]{2}[0-9]{4}"));
rxList.Add(new Regex(#"[A-Z]{3}[0-9]{2}"));
rxList.Add(new Regex(#"[A-Z]{2}[0-9]{2}[A-Z]{3}"));
Match m;
using (StreamWriter sw = new StreamWriter(#"C: \Users\user\Desktop\usersNotes\plates.csv")){
for(int Q = 0; Q < zAllPlateData.Length; Q++){
if(hsRegData.Add(zAllPlateData[Q]) == false){
//At this point we know it is a duplicate, must still match a check pattern
foreach(Regex rx in rxList){
m = rx.Match(zAllPlateData[Q]);
if(m.Success){
if(tfFirst){
tfFirst = false;
sw.Write(zAllPlateData[Q]); //First plate doesn't take a comma
}
else{
sw.Write("," + zAllPlateData[Q]); //Comma delimit subsequent plates
}
break;
}
}
}
}
}
}
}
}
This code times two methods of outputting a ~380Kb string:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Diagnostics;
namespace ConsoleApplication1
{
class Program
{
static string outbuff = "";
static void Main(string[] args)
{
{
Stopwatch exectime = new Stopwatch();
System.IO.StreamWriter file;
exectime.Reset(); exectime.Start();
file = new System.IO.StreamWriter("output.html");
for (int i = 0; i < 18000; i++)
{
outbuff += "444444444, 5555555555\n";
}
string fin = "\nString method took " + exectime.Elapsed.TotalSeconds + "s";
file.WriteLine(outbuff);
Console.WriteLine(fin);
file.WriteLine(fin);
file.Close();
}
{
Stopwatch exectime = new Stopwatch();
System.IO.StreamWriter file;
exectime.Reset(); exectime.Start();
file = new System.IO.StreamWriter("output2.html");
for (int i = 0; i < 18000; i++)
{
file.Write("444444444, 5555555555\n");
}
string fin = "\nDirect method took " + exectime.Elapsed.TotalSeconds + "s";
Console.WriteLine(fin);
file.WriteLine(fin);
file.Close();
}
}
}
}
String method took 2.2985349s
Direct method took 0.07191s
This is on a 3.5GHz CPU with 5Gb RAM.
I'm disappointed that simply buffering the output in a string is so costly!
In my real program, I need to deferr output until the string is assembled. Is there a faster way?
Yes, use a StringBuilder instead to assemble your string.
For an in-depth explanation for the performance boost see "Using the StringBuilder Class" - but basically because strings are immutable a new string is created when you concatenate, which is very expensive.
I'm trying to count the number of words from a text file, namely this, to start.
This is a test of the word count program. This is only a test. If your
program works successfully, you should calculate that there are 30
words in this file.
I am using StreamReader to put everything from the file into a string, and then use the .Split method to get the number of individual words, but I keep getting the wrong value when I compile and run the program.
using System;
using System.IO;
class WordCounter
{
static void Main()
{
string inFileName = null;
Console.WriteLine("Enter the name of the file to process:");
inFileName = Console.ReadLine();
StreamReader sr = new StreamReader(inFileName);
int counter = 0;
string delim = " ,.";
string[] fields = null;
string line = null;
while(!sr.EndOfStream)
{
line = sr.ReadLine();
}
fields = line.Split(delim.ToCharArray());
for(int i = 0; i < fields.Length; i++)
{
counter++;
}
sr.Close();
Console.WriteLine("The word count is {0}", counter);
}
}
Try to use regular expression, e.g.:
int count = Regex.Matches(input, #"\b\w+\b").Count;
this should work for you:
using System;
using System.IO;
class WordCounter
{
static void Main()
{
string inFileName = null;
Console.WriteLine("Enter the name of the file to process:");
inFileName = Console.ReadLine();
StreamReader sr = new StreamReader(inFileName);
int counter = 0;
string delim = " ,."; //maybe some more delimiters like ?! and so on
string[] fields = null;
string line = null;
while(!sr.EndOfStream)
{
line = sr.ReadLine();//each time you read a line you should split it into the words
line.Trim();
fields = line.Split(delim.ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
counter+=fields.Length; //and just add how many of them there is
}
sr.Close();
Console.WriteLine("The word count is {0}", counter);
}
}
A couple hints.
What if you just have the sentence "hi" what would be your output?
Your counter calculation is: from 0 through fields.Length, increment counter. How are fields.Length and your counter related?
you're probably getting a one off error, try something like this
counter = 0;
while(!sr.EndOfStream)
{
line = sr.ReadLine();
fields = line.Split(delim.ToCharArray());
counter += field.length();
}
there is no need to iterate over the array to count the elements when you can get the number directly
using System.IO;
using System;
namespace solution
{
class Program
{
static void Main(string[] args)
{
var readFile = File.ReadAllText(#"C:\test\my.txt");
var str = readFile.Split(new char[] { ' ', '\n'}, StringSplitOptions.RemoveEmptyEntries);
System.Console.WriteLine("Number of words: " + str.Length);
}
}
}
//Easy method using Linq to Count number of words in a text file
/// www.techhowdy.com
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace FP_WK13
{
static class Util
{
public static IEnumerable<string> GetLines(string yourtextfile)
{
TextReader reader = new StreamReader(yourtextfile);
string result = string.Empty;
string line;
while ((line = reader.ReadLine()) != null)
{
yield return line;
}
reader.Close();
}
// Word Count
public static int GetWordCount(string str)
{
int words = 0;
string s = string.Empty;
var lines = GetLines(str);
foreach (var item in lines)
{
s = item.ToString();
words = words + s.Split(' ').Length;
}
return words;
}
}
}