End of File(EOF) of Standard input stream (stdin)
stdin是否有EOF? 例如-如果我开始使用fread / read从stdin中读取,那么以下循环何时结束?
1 2 3 4 5 | while ((c = read(0, buffer, BUFSIZ)) > 0) { . . . } |
如果上述解决方案为"否",那么有什么方法可以在标准输入中添加EOF?
说到标准输入中的
1 | program <input.txt |
该文件已经有一个
编辑
根据OP提出的问题:
So does it means that stdin don't have EOF and we have to insert them manually using Ctrl+Z or Ctrl+D?
其实,是。可以将stdin(未重定向,但从控制台获取)视为无限文件-没有人知道它在哪里结束。输入文件的末尾,即输入ist stdin,必须通过Ctrl + D或Ctrl + Z逐字告知。
我从未在Windows中编程过C,所以我无法告诉您,但在bash中,当您键入数据结尾(Ctrl + D)时,该程序将获得EOF
1 while ((c = read(0, buffer, BUFSIZ)) > 0) {
您没有说
首先,getchar()实际上是getc(stdin),因此您可以从getc(FILE)中了解更多信息。 getchar()使您从输入流或标准输入中最后输入一个未处理的字符,按Enter键是' n'。如果标准输入为空,则getchar强制暂停以获取输入。
首先说一个程序,我先调用getchar(),标准输入为空,因此暂停输入。如果输入ab' n',则第一个getchar()将获得97的" a"的ascii。下次我调用getchar()时,我将得到b,然后再次getchar()将具有" n"。
为了证明这一点,请编写此代码。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | int choice; do { cout <<"Enter input:" ; choice = getchar(); cout <<"Last getchar():" << choice <<":" << (char) choice ; if( choice == '0' || choice == EOF) { cout <<"Exited loop" << endl; // EOF is ctrl+z in windows break; } }while(true); |
我确实相信stdin是全局的,因此直到调用getchar()或类似函数来清除流中的字符为止,否则如果在其他地方使用getchar(),可能会导致错误。正如人们提到的,您可以使用gets(char [])将所有字符放到换行符中,直到字符数组为止。问题是您需要一个比输入大的char [],否则会出错。不错的是,gets(char [])会清除标准输入,因此您可以创建一个杜比缓冲区来清除标准输入或对其进行处理。
我希望这是有益的。
您的解决方案被标记为C ++,所以这里有一些C ++。
1 2 3 4 | std::string lols; while(!(std::cin >> lols).eof()) { // This loop will end when EOF is reached // Process string } |
测试EOF的方法是检查fread的返回值,然后使用feof:
1 2 3 4 5 6 7 8 9 10 | while( fread( ... ) ) { // loop so long as fread does not return zero // do something } if ( feof( stdin ) ) { // read failed because of EOF } else { // some other error } |