MENU











Monday, 23 December 2013

week 12 oops

Week 12 solutions

12a) Write a C++ program to display the contents of a text file.


File: hello.txt
               Hello
**** Welcome to C++ programming ****


Program:
#include<iostream>
#include<fstream>
using namespace std;
int main()
{ 
       ifstream in("hello.txt");
       cout<<in.rdbuf(); //rdbuf() function outputs all the contents of the file
       return 0;
}
output:
               Hello
**** Welcome to C++ programming ****


12 b) Write a C++ program that counts the characters, lines and words in the text file.

file:wish.txt
Hello
Welcome to C++ programming
happy coding

program:

#include<iostream>
#include<fstream>
#include<cctype>
using namespace std;
int main()
{
       int data,count=0,words=0,lines=0;
       ifstream file;
       file.open("wish.txt",ifstream::in);
       char c=file.get();
       cout<<"\nContents of the file\n";
       while(!file.eof())
       {
           cout<<c;
      
           if(isalnum(c))
              count++;
           if(isspace(c))
              words++;
           if(c=='\n')
              lines++;
           c=file.get();
       }
      lines++,words++;
      file.close();
      cout<<"\n\n Characters :"<<count;
      cout<<"\n Lines :"<<lines;
      cout<<"\n Words :"<<words;
      return(0);
}

output:
Hello
Welcome to C++ programming
happy coding

characters:37
Lines:3
words:7



12 c) Write a C++ program that produces the sum of all the numbers in a file of whitespace
separated integers.

File:num.txt
1 2 3 4 5 6 7 8 9 10

program:

#include<iostream>
#include<fstream>
using namespace std;
int main(void)
{
     int sum=0;
     ifstream file("num.txt");
     int x;
     while(!file.eof())
     {
          file>>x;
          cout<<x<<" ";
          sum+=x;
     }
     file.close();
     cout<<"\nSum of all integers is "<<sum;
}

output:
1 2 3 4 5 6 7 8 9 10
Sum of all integers is 55