终端中的 Ctrl+Z 行为 [英] Ctrl+Z behaviour in terminal

查看:29
本文介绍了终端中的 Ctrl+Z 行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

string s;而(getline(cin,s)){cout<<——"<<结束for(auto c: s) cout <<int(c)<<结束;}cout<<"退出";

如果我的输入是Ctrl+Z,那么我按回车一次,我的程序立即退出.

^Z退出

如果我在按Ctrl+Z之前输入一个字符,那么我必须按两次回车,我的程序不会退出.

s^Z---11526

我一直将 Ctrl+Z 解释为 EOF 字符.getline 将继续直到它到达这个字符,此时 getline 测试为 false 并且我的程序将退出.我很好奇为什么我的程序将 Ctrl+Z 解释为

string s;
while(getline(cin,s)){
    cout << "---" << endl
    for(auto c: s) cout << int(c) << endl;   
}
cout << "Exiting";

If my input is Ctrl+Z, then I press enter once, and my program exits immediately.

^Z
Exiting

If I enter a character before pressing Ctrl+Z, then I have to press enter twice, and my program does not exit.

s^Z

---
115
26

I had always interpreted Ctrl+Z as the EOF character. getline would continue until it reaches this character, at which point getline tests false and my program would exit. I'm curious why my program interprets Ctrl+Z as the substitute character 26, depending on whether there is a preceding character or not, and why it was necessary for me to press Enter twice in the second example?

解决方案

26 is code of ^Z on your platform , and ^Z is a EOF marker for terminal, that's true. Characters with codes less than 32 are control characters for ASCII -compatible platform, I hope you know that. 26 isn't a substitute character, it's actual control code, ^Z or some "bug" character are substitutes. getline reads input until EOL (end-of-line, designated as CR by ASCII) or EOF (end of file, end of stream, designated as SUB) is encountered in stream, so ^Z is read with the second call of getline. That behavior is absolutely correct.

It is defined by platform (or, more precisely, by terminal type) if characters are sent to input buffer immediately or after some flush command occurred. Usual cause of buffer flush is EOL character, that's your ENTER (CR - Carriage return). Tat's why program receives EOF after Enter in your case. Note that some platform use LF (line feed) as EOL, and some - a pair of LF+CR. C literal '\n' is to be correctly translated into particular EOL marker.

Note, that you can use different delimiter:

template< class CharT, class Traits, class Allocator > 
std::basic_istream<CharT,Traits>& getline( 
         std::basic_istream<CharT,Traits>& input,
         std::basic_string<CharT,Traits,Allocator>& str,
         CharT delim );

ASCII table with substitute Control+ :

这篇关于终端中的 Ctrl+Z 行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆