\n的C ++测试

编程入门 行业动态 更新时间:2024-10-21 03:27:00
本文介绍了\n的C ++测试的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在尝试学习C ++,一种练习是构建一个命令行工具,该工具接受用户输入并将其存储在char数组中,直到用户输入空白行为止。我认为我的骨骼是正确的,但是无论出于何种原因,我的身体都在不断运转。我的代码如下:

I'm attempting to learn C++ and one exercise is to build a command line tool that accepts user input and stores it in a char array until the user enters a blank line. I think I have the skeleton right but for whatever reason my while runs continuously. My code is as follows:

char a[256]; //while the first character isn't a new line while (a[0] != '\n') { //get the char array cin >> a; cout << a; }

任何帮助将不胜感激。

推荐答案

使用 operator>> 无法检测到换行符。对于大多数类型,它使用空格作为分隔符,并且不区分空格,制表符或换行符。改用getline:

You can't detect newlines with operator>>. For most types, it uses whitespace as a delimiter, and it doesn't differentiate between spaces, tabs or newlines. Use getline instead:

for (std::string line; std::getline(std::cin, line); ) { if (line.empty()) { // if the line is empty, that means the user didn't // press anything before hitting the enter key } }

更多推荐

\n的C ++测试

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

发布评论

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

>www.elefans.com

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