终端中的 Ctrl+Z 行为

编程入门 行业动态 更新时间:2024-10-27 02:26:37
本文介绍了终端中的 Ctrl+Z 行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送ChatGPT账号..

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屋!

更多推荐

[db:关键词]

本文发布于:2023-04-25 20:41:39,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1123445.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:终端   Ctrl

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!