displayText problem with loop
Mar 11, 2016 at 3:38am UTC
I'm writing a program to read from a file ex: 1 2 3 and display it backwards. Everything is working fine, except for my displayText function. Any suggestion on why that function is not working?
Thanks,
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
#include <iostream>
#include <fstream>
using namespace std;
void readFile(char filename[])
{
ifstream fin(filename);
if (fin.fail())
cout << "you fail\n" ;
char text[256];
while (!fin.eof())
{
fin >> text;
}
fin.close();
}
void displayText(char text[256])
{
int i = 0;
while (text[i])
i++;
for (i--; i >= 0; i--)
cout << text[i] << endl;
}
int main()
{
char filename[256];
cout << "Please enter file name: " ;
cin >> filename;
char text[256];
readFile(filename);
displayText(text);
return 0;
}
Last edited on Mar 11, 2016 at 5:37am UTC
Mar 11, 2016 at 8:42am UTC
Line 19: Your are filling a local variable that does not exist outside readFile(...)
So instead of having a local variable (on line 15) pass this as a parameter:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
#include <iostream>
#include <fstream>
using namespace std;
void readFile(char text[256], char filename[]) // Note
{
ifstream fin(filename);
if (fin.fail())
cout << "you fail\n" ;
char text[256]; // Note
while (!fin.eof())
{
fin >> text;
}
fin.close();
}
void displayText(char text[256])
{
int i = 0;
while (text[i])
i++;
for (i--; i >= 0; i--)
cout << text[i] << endl;
}
int main()
{
char filename[256];
cout << "Please enter file name: " ;
cin >> filename;
char text[256];
readFile(text, filename); // Note
displayText(text);
return 0;
}
Mar 11, 2016 at 4:21pm UTC
Thanks for pointing that out.
I was able to do what I wanted.
Topic archived. No new replies allowed.