Code to read from a file doesn't work

Hello

I want to be able to read from a file, and put the content from that file in the terminal, I use streams. :)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>
#include <fstream> 

using namespace std;
int main() {
	char fileContent[100];
	cout<<"FTPspider"<<endl;
	ifstream file;
	file.open("test.txt");
	if (file.is_open()) {
		while(! file.eof()) {
			file >> fileContent;
			cout << fileContent;
		}
	}
	file.close();
}


The code doesn't work or doesn't give a valid output (a weird character - probably declared variable fileContent wrong).


Thanks for all your help! :)

Thanks for reading,
Niely
1
2
	ifstream file;
	file.open("test.txt");
You can simply use the constructor instead ifstream file("test.txt"); //I would also store the filename into a variable

I would also remove line 10 and change line 11 to while(file >> fileContent) line 16 is also not needed since the destructor will call it, I would only call manually if you are going to check if it failed on close or something.

As for the problem you are having I see no problem with a character array though I would suggest using a std::string so something like:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>
#include <string>
#include <fstream>

int main()
{
    std::string const filename = "test.txt";
    
    std::ifstream in(filename); //if you don't have c++11 enabled you need filename.c_str()
    std::string input = "";
    while(in >> input)
    {
        std::cout << input << ' '; //how ever you want displayed you can also use getline to read instead of operaor >> if you want an entire line
    }
    
    return 0;
}
^Thanks! :)
Works like a charm, but now an a bit off-topic question.

I have a void and the main function, how can I go from the void to the main?

1
2
3
4
5
6
7
8
void a() {
//Code
main();
}

int main() {
//Code
}


How to do it? :)
You don't. main() should be where everything starts. Don't call it from another function, and don't call it recursively.

To go back to main, you have a function called from main that returns a value (or changes something).
Last edited on
^Could you give a small example of that? :)
Sure, I would suggest reading the site's tutorial on functions though
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>
void foo()
{
    std::cout << "Hello world!" << std::endl;
}
int square(int arg)
{
    return arg*arg;
}

//Everything starts here
int main()
{
    //Caling foo
    foo();
               //Calling another function
    std::cout << another_function(4) << std::endl;
    return 0;
}
Last edited on
Thanks! :)
(Again)

Helped me out!
Topic archived. No new replies allowed.