Terminating console input in C and C++

Hi, I was having this exercise where I had to write some input/output functions in C++ but call C functions to do the job and throw an exceptions if errors occurred.

So now I have to write to file using fprintf and I suppose I'll use scanf to get input from console

When I was reading file I used this simple code (don't know if it's the best way to go)
1
2
3
4
	FILE* fp = open_file(filename, "r");

	for (char ch = 0; fscanf(fp, "%c", &ch) != EOF;)
		printf("%c", ch);


I think than when I'm getting some random text from console I also have to work with chars coz I don't know if next thing I'm getting is char or float or anything else from the input

When I have to do something like this in C++ I would use something like this

1
2
3
4
for(std::string line; std::getline(std::cin, line);){
    if(line == "__STOP__") break;   // woud use some keyword to terminate input
    //do something with line for example write line to some file
}


Is there some smart way to do the above example without using some terminating string?

How can I read some long random texts from console using scanf("%c", &ch)?

Is there a way to trigger EOF while using scanf("%c", &ch)?

Is there a way to trigger std::cin.eof if I'm using std::getline(std::cin, line) or even std::cin >> ch //char ch;

I hope my questions is clear. As always any help appreciated.
When reading from the keyboard, you can simulate end-of-file by pressing ctrl-D or possibly ctrl-Z.
Last edited on
Ty very much man. It is kind of working but in this specific function
1
2
3
4
5
6
7
8
9
10
void write_to_file(const std::string& filename) {

	FILE* fp = open_file(filename, "w"); // throws exception in case cant open

	for (char ch = 0; scanf("%c", &ch) == 1;) {
		fprintf(fp, "%c", ch);
	}

	close_file(fp);			     // throws exception in case cant close
}

when I enter the text and in the end press ctrl + z and than press enter its not working the 1st time. I have to press ctrl + z and enter again and only than it works. Any ideas why that is so?
Last edited on
ctrl+z is recognized as eof only at the beginning of a line in Windows. A line should end with a newline character, not a ctrl+z character.
Cool, tnx a lot man!
Topic archived. No new replies allowed.