C++ Help about loop

I have a program which works but it will not continue or start over. After I input the first function it exit without starting over and over until I tell it to exit. Here is my program.

#include<iostream>
#include<fstream>
#include<cstdlib>
#include<stdio.h>
#include<stdlib.h>
#include<string.h>

using namespace std;

int main()
{
ifstream inFile ("e:/Text1.txt", ios::in);
char sentence[80];

if(!inFile)
{
cerr<<"File Text1.txt could not be opened"<<endl;
exit(1);
}

inFile.getline(sentence,80);

cout<<endl;
cout<<"The file Text1.txt contains the following sentence:";
cout<<endl;
cout<<sentence;
inFile.close();
cout<<endl;

cout<<"Please enter a lowercase letter between (a-z):";
char letter;
cin>> letter;


char* ch_ptr;
int counter_letter = 0;
for (ch_ptr = sentence; *ch_ptr != '\0'; ++ch_ptr);

if (*ch_ptr==letter)
++counter_letter;

cout<< "The number of occurences of the letter " << letter << " is " << counter_letter << endl << endl;










return 0;

}
for (ch_ptr = sentence; *ch_ptr != '\0'; ++ch_ptr);

This line doesn't actually do anything because you ended the for() statement with a semicolon.

You probaby wanted:

1
2
3
for(ch_ptr = sentence; *ch_ptr != '\0'; ++ch_ptr)
  if (*ch_ptr==letter)
    ++counter_letter;
Seems like your path isn't correct for windows:

[e:/Text1.txt]

should probably be:

[e:\\Text1.txt].

Notice the use of double [\\] as opposed to using [\] since [\] is an escape sequence character.

Also your use of [if (!inFile)] doesn't seem right to me.

You should rather test with one of the ifstream methods like:

[if (!inFile.good()) ...

The rest of your program looks fine to me.
iostream is the c++ equivalent to stdio.h and cstdlib is the c++ equivalent to stdlib.h. string.h is just string in c++. so you don't need the first two .h files and if you want proper syntax the third
using / in paths on windows works fine and makes the code more compatible with other systems.
Last edited on
Topic archived. No new replies allowed.