我怎样才能得到一个带有'\ n'的字符串(Enter) [英] How can i get a string with the '\n' ( Enter )

查看:224
本文介绍了我怎样才能得到一个带有'\ n'的字符串(Enter)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

嗨.
如何获取带有"\ n"(输入)的字符串?
例如,在这段代码中,只能读取一行内容,而不能读取更多内容.

Hi.
How can i get a string with the ''\n'' ( Enter )?
for example, in the this code, just can read the one of lines and not more.

#include <iostream>
#include <string>
int main(){
    string str;
    std::cin>> str;
}


或者换句话说,获取字符串和字符的解决方案是什么?
谢谢.


or in other words, what is the solutions for getting the strings and characters?
Thanks.

推荐答案

通常,我会同意loctrice的观点,即使用 std::getline是一个好主意,而使用std::getline跨所有类型的流. FREX Windows控制台只能通过在新行输入CTRL^Z来使其处于文件状态的末尾,而对于文件,它可以位于任何位置,而并不总是像在控制台上输入换行符后一样.

所以你对此能做些什么?好好滚动自己并不难,尤其是如果您使用的是C ++标准库中的内容.
While normally I''d agree with loctrice that using std::getline is a good idea, doing what you want is a real pain using std::getline across all types of streams. FREX windows consoles can only be put into a end of file state by entering a CTRL^Z at a new line while for files it can be anywhere and not always after a newline is entered as on the console.

So what can you do about it? Well rolling your own isn''t too hard, especially if you use what''s already in the C++ standard library.
std::istream &read_line_with_newline( std::istream &str, std::string &line  )
{
    for( char next = 0; str && next != '\n'; )
    {
        str >> std::noskipws >> next;
        line += next;
    }

    return str;
}

当您使用fgetchar进行此类操作时,可能会回闪到C ++之前的日子. noskipws操纵器意味着您在阅读时不要忽略whitepace,将其作为普通字符进行处理.

为英文版本编辑失败,并再次出现错字,任何人都认为这不是我的母语!

It''s a bit of a flashback to pre-C++ days when you''d use fgetchar to do this sort of thing. The noskipws manipulator means that when you''re reading don''t ignore whitepace, process them as ordinary characters.

Edited for English fail and again for a typo, anyone''d think it wasn''t my mother tongue!


您发布的代码部分将不会阅读一行,它将读取为空格字符.一个有效的选择是使用getline并更改定界符.您还可以将getline放入while循环中.


此处是c ++的不错参考和论坛 [
The code part you posted will not read a line, it will read to a space character. A valid option would be to use getline and change the delimiter. You could also put the getline in a while loop.


Here is a great reference and forums for c++ [^]


这篇关于我怎样才能得到一个带有'\ n'的字符串(Enter)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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