FoodForFutureGeeks

Friday 29 June 2012

Program to Read a file line by line in C++


#include<iostream>
#include<fstream>
#include<string>
using namespace std;
int main()
{
string strfile="filenamewithabsolutepath.txt";
 ifstream ifptr;
 ifptr.open(strfile);
if(!ifptr.is_open())
{
 cout<<"Unable to open file\n";
 }
 else{
 //read the file till the end
    while(!ifptr.eof())
    {
     string line;
     getline(ifptr,line);
     cout<<"line:"<<line<<"\n";
    }//end of while
   }//end of else
   return 0;
 }//end of main

Friday 22 June 2012

Program to Reverse a String

Code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#include<iostream>
using namespace std;
int main()
{
char* original_string="abcdefg";
char* reverse_string;
char* temp;
int length_original=0;
int length_reverse=0;
temp=original_string;
 
//find the length of string
while(*temp!=NULL)
{
 temp++;
length_original++;
}
//assign memory to reverse_string
reverse_string=new char[length_original];
while(length_original>0)
{
 reverse_string[length_reverse++]=*--temp;
 length_original--;
}
//store null as last character
reverse_string[length_reverse]='\0';
cout<<"Original string:"<<original_string;
cout<<"\nReverse string:"<<reverse_string;
return 0;
}

Output:

Original string:abcdefg
Reverse string:gfedcba