Implementing functions to read text file

Hi guys, i'm new at C++ and i'm currently learning how to integrate functions to read consecutive integers off a .txt file.

This is the part I DON'T get. Basically I have a function to detect a palindrome number, but how do i get it to be used to read an external .txt file? I listed the function before the main() . But where do i put the file stream and how do i link it to read the .txt file on my desktop?

Reading the numbers and checking if they are palindromes are 2 totally different things.
I would declare the input stream in main, read the numbers in a loop and call the function for palindromes on each number.
Hello toplel,

It would be helpful if you post the code that you have, so people can see what you are doing and better tell you what you can do.

Just in case since you are new:


PLEASE ALWAYS USE CODE TAGS (the <> formatting button), to the right of this box, when posting code.

Along with the proper indenting it makes it easier to read your code and also easier to respond to your post.

http://www.cplusplus.com/articles/jEywvCM9/
http://www.cplusplus.com/articles/z13hAqkS/

Hint: You can edit your post, highlight your code and press the <> formatting button.

You can use the preview button at the bottom to see how it looks.

I found the second link to be the most help.



Andy

Edit:

P.S. do not forget to show the input file you are using. This way everyone can use the same information. It also helps to know what the file looks like when it comes to reading the file.
Last edited on
Hi andy, I was more looking for a general understanding of the concept, but here is my code.

Basically I have a function to check if a number is a palindrome, and i am supposed to run a list of numbers from a .txt file through this function. in the end results its supposed to print out how many numbers are palindromes and how many are not. My code is still incomplete of course but any advice will be very helpful thanks!

___________________________

#include <iostream>
#include <fstream>

using namespace std;

bool numberPalindrome(int x)
{
int palinDrome = 0, notPalinDrome = 0;
int y, r = 0;

y = x;

while (y != 0){

r = r * 10;
r = r + y % 10;
y = y / 10;

}

if (x == r) {
palinDrome +=;
else
notPalinDrome +=;
}
}

int main ()
{
int f;
ifstream inFile;

inFile.open("test1.txt");
if (!inFile){
cout << "Unable to open file";
exit(1);
}
1) Please use code tags to make your code readable. Andy already asked you to do this, but since you ignored him, I'll ask again:

http://www.cplusplus.com/articles/z13hAqkS/

2) That code you've posted is incomplete. At the very least, it's missing a closing brace.

3) Here's a tutorial on how to read from a file in C++ :

http://www.cplusplus.com/doc/tutorial/files/
Last edited on
Topic archived. No new replies allowed.