Examples of File Use
Below are standard examples for reading in a file in several different languages.
Visual BASIC
Option Explicit
Private Sub Form_Paint()
Dim amount as Single, bal as Single, charge as Single, op as String
Open "Z:\check.txt" For Input As #1
Input #1, amount
bal = amount
charge = 0
Print "Begin", " ", A
Input #1, op
Do While op <> "Q"
If op = "D" Then
Input #1, amount
bal = bal + amount
Print "D", amount, bal
Else
Input #1, amount
bal = bal - amount
Print "C", amount, bal
If bal < 0 Then
charge = charge + 15
End If
End If
Input #1, op
Loop
bal = bal - charge
Print "Charges", charge, bal
End Sub
C++
#include <fstream.h> // class ifstream, and the cout object
#include <iomanip.h> // setw and other manipulators
ifstream fin("Z:\\check.txt"); //use fin in the same way as cin
int main() {
int a,bal,charge;
char op;
fin>>a;
bal = a; charge = 0;
cout << setw(9) << "Begin" << setw(9) << " " << setw(9) << a << endl;
fin >> op;
while(op != 'Q'){
if( op == 'D' ){
fin >> a;
bal = bal + a;
cout << setw(9) << "D" << setw(9) << a << setw(9) << bal << endl;
}else{
fin>>a; bal = bal - a;
cout << setw(9) << "C" << setw(9) << a << setw(9) << bal << endl;
if( bal < 0 ) charge = charge + 15;
}
fin >> op;
}
bal = bal - charge;
cout << setw(9) << "Charges" << setw(9) << charge << setw(9) << bal << endl;
return 0;
}
Java
import java.io.*; //File
import java.util.*; //Scanner
public class Check {
public static void main(String[] args) throws Exception{
new Check();
}
Check( ) throws Exception {
Scanner sc = new Scanner(new File("Z:/check.txt"));
int bal = sc.nextInt();
int charge = 0;
System.out.println("Begin "+" "+bal);
while (true) {
char ch = sc.next().charAt(0);
if(ch == 'Q') break;
else{
int amt = sc.nextInt();
if(ch == 'C') {
bal = bal - amt;
if(bal < 0) charge += 15;
}else{
bal = bal + amt;
}
System.out.println(ch + " " + format9(amt) + bal);
}
}
bal = bal - charge;
System.out.println("Charges "+format9(charge)+bal);
}
String format9(int v){
String s = "" + v;
while(s.length() < 9) s = s + " ";
return s;
}
}
Visual Basic .NET
Dim oRead As System.IO.StreamReader
oRead = IO.File.OpenText("test.txt")
While oRead.Peek() <> -1
Console.WriteLine(oRead.ReadLine())
End While