Okay, so here's the deal. I made a program that loops through a text file. Now all I need is when if finds that word is to print the line number that the word was first found on, or 0 if it isn't found.
I'm pretty dang confused on this as of now and I don't have a lead. Help is appreciated. :)
The extraction operator will only read a single word (white space delimited character sequence) from the stream. That is, the line counting scheme you employ does not count lines, but words. You could instead use the getline function for strings to extract each line in a string. Then you can search the extracted string for occurrence of the word in some inner loop. The outer loop will count the lines.
#include <iostream>
#include <fstream>
#include <cstdio>
#include <cstring>
usingnamespace std;
int main(int argc, char** argv)
{
char FileName[256];
char SearchWord[256];
int counter = 0;
cout << "Enter the word you want to search for: ";
cin >> SearchWord;
cout << "\n\n";
cout << "Enter the name of file you want to open: ";
cin >> FileName;
cout << "\n\n";
ifstream FileSearch;
FileSearch.open(FileName);
if(!FileSearch)
{
cout << "File was unable to be opened.\n";
}
else{
while(!FileSearch.eof())
{
counter++;
string temp;
FileSearch >> temp;
if(temp == SearchWord)
{
cout << SearchWord << " found on line: " << counter << "\n\n";
break;
}
if(temp != SearchWord)
{
if(FileSearch.eof())
{
cout << 0;
}
}
}
}
return 0;
}
It will open a file, lets say you enter "Students" it will open a file named Students. If you try "Students.txt", and you have a a text file named "Students.txt" in the same directory, it won't open. What have I done wrong?
From which directory do you launch your app. Your working directory (initially the one in which you launch the executable) does not have to be the directory where the executable resides.
I have no idea. The code that opens the file looks fine. Are you sure that the extension is not there when you think you have removed it? (I know this is "check the cables" troubleshooting, but still.) Some OSes (read Windows) hide the extensions of registered document types. (unless instructed otherwise)
Sorry for being unhelpful, but I am shooting at the dark.
string FileName
..............
cout << "Enter the name of file you want to open: ";
getline (cin, FileName);
..............
FileSearch.open(FileName.c_str());
that method works all the time for me
also, if you right click on resources you can add your data files that way and they will be conveniently available
Also I've run into something similar myself, what was happening is I had copied the original file elsewhere and my program was sniping (opening from a distance lol{it ended up my fault of course}) the file. What I would try is to make a completely new file and name it something completely random, just to make sure there aren't any duplicates, then give it a try. When you find out it works great with the new files, troubleshoot the old files.