Hello everyone :)
My C++ class just started learning strings the other day. We were given a simple program that's due tomorrow, but I'm having a bit of trouble with it. I've emailed my teacher, who says I'm on the right track but need to fix something in my while loop.
The program asks the user to enter all or part of a city name. Then the program locates the file cities.txt and ouputs any matches. At the end, the matches are added up for a total.
This is what I have:
#include <iostream>
#include <string>
#include <fstream>
#include <conio.h>
using namespace std;
int main()
{
ifstream file;
string s, city, bigstring, substring;
int count = 0; // Count variable to count the number of matches within the file.
file.open("c:\\cities.txt"); // Opens the file cities.txt.
cout << "Enter all or part of a city name: ";
getline(cin,city); // User-inputted city name.
if (bigstring.find(substring) != -1) // Returns the position of substring within bigstring. If substring doesn't exist in bigstring, -1 is returned.
while (getline(file,s)) // Read a line. If successful, enter the loop.
{
cout << s << endl;
count++
}
cout << "There were " << count
<< " matches in the file" << endl;
getch();
return 0;
}
He said that my problem is this:
while (getline(file,s)) // Read a line. If successful, enter the loop.
{
cout << s << endl;
count++;
}
That, "That's printing every line you read. Wouldn't you want to conditionally print the city instead?"
But, I feel like I've tried everything...any suggestions?