Hello. I am currently looking to write a program that reads the number input by a user, searches that number within the file, then outputs the first name given on the desired line.
Here is the text file data:
3
Titanic
Kate Winslet
Leonardo Dicaprio
Cameron
cameron
20th Century Fox
2
Donald Duck 1
Mickey Mouse 2
Minnie Mouse 3
Goofy Dog 4
You should try reading the txt file into a string then use the find() function to see if it exists..
1 2 3 4 5 6 7 8 9
//set up variable userdata
string buffer;
//read file into buffer
if(buffer.find(userdata,0) != string::npos){
//whatever should happen if found
}
else{
//what should happen if not found
}
When I run this code, I'm only able to input 3 and actually get the if statement to run. When I put in 1,2, or 4, I just get my else statement.
Any suggestions?
The reading of the text file isnt really correct I dont think. Also cin is space terminated so anything with a space in it will mess up your results, that is why i used getline. See if fixing the text file reading helps.. Im going to look for something to help you if you wait a moment
The way I open the file doesn't have an effect on the output. It still reads into my program just fine.
As for cin, did you mean that I should getline(cin,memberID);, then I still get the same output when this program is ran.
Not exactally sure. The way this works is the find function searches for whatever you tell it to search for and if it is not found it returns string::npos else it returns the position of what it founds. So if you put it 1 it should return the position of 1 in the file which != string::npos which should make the if statement be true. I am going to run the program and see what I can come up with
I ran the program and debugged it with xcode on Lion and with that IDE there is a tool where I can view the memory of variables, so I looked at both memberBuffer and memberFile and neither contained the txt file. Try fixing the reading of the text file and that should help. Also you may want to clear the memory of those two variables before they are used, string.clear() should do the trick.