c 1 introduction to programming and the c language

c 1 introduction to programming and the c language


DisciplinaFísica Básica I826 materiais10.228 seguidores
Pré-visualização50 páginas
Write();
Read();
}
public static string GetLine()
{
Console.Write("? ");
return Console.ReadLine();
}
public static void PutLine(string line)
{
Console.WriteLine(line);
}
public static void Write()
{
StreamWriter writer = new StreamWriter("Tekst.txt");
string line = GetLine();
while (line.Length > 0)
{
writer.WriteLine(line);
line = GetLine();
}
writer.Close();
}
EXPERIENCE THE POWER OF 
FULL ENGAGEMENT\u2026
 RUN FASTER.
 RUN LONGER..
 RUN EASIER\u2026
READ MORE & PRE-ORDER TODAY 
WWW.GAITEYE.COM
Challenge the way we run
1349906_A6_4+0.indd 1 22-08-2014 12:56:57
Download free eBooks at bookboon.com
C# 1 Introduction to programming and the C# language 
224 
Text files
public static void Read()
{
StreamReader reader = new StreamReader("Tekst.txt");
string line = reader.ReadLine();
while (line != null)
{
PutLine(line);
line = reader.ReadLine();
}
reader.Close();
}
}
}
Explanation
Note first that there is a using statement for System.IO. It will typically be the case in all applications 
that use files.
The method GetLine() corresponds to get data in the algorithm, and it writes a simple prompt in the 
form of a question mark on the screen and then performing a ReadLine(). The method returns a string 
with the user\u2019s input.
The method Write() creates and opens a text file for writing:
StreamWriter writer = new StreamWriter("Tekst.txt");
The file is named Tekst.txt and is created in the same directory as the program\u2019s exe file. The file name 
is a parameter to the constructor for a class of the type StreamWriter, which represents a text file which 
you can write to. You can specify a full path to the file if you want it to be placed somewhere else. After 
the user enters a line, it is written to the file using the writer and the method WriteLine():
writer.WriteLine(line);
Note that this method has the same properties (the same overrides) as the corresponding method in the 
Console class and, therefore, also can print a formatted text to a file.
After the loop is terminated, the file is closed.
There are a few things you should be aware of. When the file is opened by creating a StringWriter object, 
the file is created if it does not exist. If the file however, has already been created, it will be overwritten. 
If you do not want the file is overwritten, you can specify a second parameter to the constructor, which 
opens the file in append mode. 
Download free eBooks at bookboon.com
C# 1 Introduction to programming and the C# language 
225 
Text files
There is then added to the end of the file. When you write a line in the file with the WriteLine(), the 
string\u2019s characters are written to the file followed by a newline. Finally, you should notice the last Close() 
statement. It is necessary because in fact the data are not written physical to the file for each WriteLine(), 
but instead to a buffer in the memory. Close() causes, in addition to free the connection to the file, that 
the content of the buffer is written to the file.
The method Read() shows how to read the content of a text file and print it on screen. Here corresponds 
the method PutLine() to apply the algorithm\u2019s use line, and in this case the method is tedious and do 
nothing more than to write the string as a line on the screen. The method Read() starts to open the file 
for reading with a StreamReader object:
StreamReader reader = new StreamReader("Tekst.txt");
Then the method trys to read a line in the file:
string line = reader.ReadLine();
If it goes well \u2013 line is different from null \u2013 the method PutLine() is executed with line as a parameter 
and then the program attempts to read the file again. The result is that the loop is repeated until there 
are no more data in the file. Finally, the file is closed.
This is actually what there is to say about text files, but it is clear that how to get data, and how to treat 
a line that is read from the file depends on the specific task.
Exam54
Write a comma separated file
The following example is in principle identical to the above, but the treatment of data is not quite so 
simple, and it is also a slightly more realistic example of how you can meet text files. Actually, there are 
two programs, and the next program is concerning the same example.
A comma separated file is a text file that contains a number of lines where each line consists of several 
elements, and where the individual elements are separated by a delimiter. The delimiter will often be a 
comma (hence the name) but it can in principle be anything, just to be a symbol that does not occur in 
the individual text elements. In this case a semicolon is used as a delimiter.
Download free eBooks at bookboon.com
Click on the ad to read more
C# 1 Introduction to programming and the C# language 
226 
Text files
The first program will create a text file where the user enters a phone number followed by one or more 
product amounts as you can think of sales and thus indicate sales to a particular phone number. For 
each phone number the program writes a line in the file consisting of the telephone number and product 
amounts and with the fields separated by semicolons. The result could be the following file:
Note that the same telephone number might well appear several times, and that there may be lines with 
just a phone and no amounts.
The code is as follows:
class Program
{
static void Main(string[] args)
{
StreamWriter writer = new StreamWriter("F:\\Temp\\Salg.txt", true);
string line = PhoneNumber();
while (line.Length > 0)
Designed for high-achieving graduates across all disciplines, London Business School\u2019s Masters 
in Management provides specific and tangible foundations for a successful career in business. 
This 12-month, full-time programme is a business qualification with impact. In 2010, our MiM 
employment rate was 95% within 3 months of graduation*; the majority of graduates choosing to 
work in consulting or financial services. 
As well as a renowned qualification from a world-class business school, you also gain access 
to the School\u2019s network of more than 34,000 global alumni \u2013 a community that offers support and 
opportunities throughout your career.
For more information visit www.london.edu/mm, email mim@london.edu or 
give us a call on +44 (0)20 7000 7573.
Masters in Management
The next step for 
top-performing 
graduates
* Figures taken from London Business School\u2019s Masters in Management 2010 employment report
Download free eBooks at bookboon.com
C# 1 Introduction to programming and the C# language 
227 
Text files
{
writer.WriteLine(line);
line = PhoneNumber();
}
writer.Close();
}
static string PhoneNumber()
{
while (true)
{
Console.Write("Enter phone no. as 8 digits: ");
string phone = Console.ReadLine().Trim();
if (phone.Length == 0) return "";
if (PhoneOk(ref phone))
{
StringBuilder builder = new StringBuilder(phone);
double amount = Amount();
while (amount > 0)
{
builder.Append(string.Format(";{0:F2}", amount));
amount = Amount();
}
return builder.ToString();
}
Console.WriteLine("Illegal phone no.");
}
}
static bool PhoneOk(ref string tlfnr)
{
tlfnr = tlfnr.Trim();
StringBuilder builder = new StringBuilder();
for (int i = 0; i < tlfnr.Length; ++i)
if (tlfnr[i] >= '0' && tlfnr[i] <= '9')
builder.Append(tlfnr[i]);
else if (tlfnr[i] != ' ')
return false;
tlfnr = builder.ToString();
return tlfnr.Length == 8;
}
static double Amount()
{
while (true)
{
Console.Write(&quot;Enter the amount: &quot;);
try
{
string text = Console.ReadLine().Trim();
if (text.Length == 0) return 0;
return Convert.ToDouble(text);
}
catch
{
Console.WriteLine(&quot;Illegal amount&quot;);
}
}
}
}
Download free eBooks at