zoukankan      html  css  js  c++  java
  • C/C++中的行读取

    在C语言里面一直很容易混淆的,gets和fgetS的区别:

    char * fgets ( char * str, int num, FILE * stream );
    Reads characters from stream and stores them as a C string into str until (num-1) characters have been read or either a newline or the end-of-file is reached, whichever happens first.

    A newline character makes fgets stop reading, but it is considered a valid character by the function and included in the string copied to str.

    A terminating null character is automatically appended after the characters copied to str.

    Notice that fgets is quite different from gets: not only fgets accepts a stream argument, but also allows to specify the maximum size of str and includes in the string any ending newline character.

    char * gets ( char * str );
    Get string from stdin
    Reads characters from the standard input (stdin) and stores them as a C string into str until a newline character or theend-of-file is reached.

    The newline character, if found, is not copied into str.

    A terminating null character is automatically appended after the characters copied to str.

    Notice that gets is quite different from fgets: not only gets uses stdin as source, but it does not include the ending newline character in the resulting string and does not allow to specify a maximum size for str (which can lead to buffer overflows).

    简单说来,fgets能够指定最大输入字符数(num - 1),他们都在遇到换行符的之后终止,fgets把换行符也读进字符串里,gets简单的丢掉换行符。

    C++中对应的有cin的四个函数:

    istream & get(char *, int, char);
    istream & get(char *, int);
    istream & getline(char *, int, char);
    istream & getline(char *, int);

    这里,get和getline都不会把换行符读进去,但是get会把换行符(或者指定的其他分隔符)留在流里面,而getline会把换行符从流中读取出来并丢弃。



  • 相关阅读:
    HDU 3681 Prison Break 越狱(状压DP,变形)
    POJ 2411 Mondriaan's Dream (状压DP,骨牌覆盖,经典)
    ZOJ 3471 Most Powerful (状压DP,经典)
    POJ 2288 Islands and Bridges (状压DP,变形)
    HDU 3001 Travelling (状压DP,3进制)
    POJ 3311 Hie with the Pie (状压DP)
    POJ 1185 炮兵阵地 (状压DP,轮廓线DP)
    FZU 2204 7
    POJ 3254 Corn Fields (状压DP,轮廓线DP)
    ZOJ 3494 BCD Code (数位DP,AC自动机)
  • 原文地址:https://www.cnblogs.com/hustxujinkang/p/4186033.html
Copyright © 2011-2022 走看看