C++字符串输入函数小结

做了一些字符串类型的题目,发现在字符串类型的题目中

如何进行输入输出是很重要的,查找资料的过程中看到了这篇博文

觉得写的很好,就给转过来了

以下为正文:



原创 http://hi.baidu.com/atomxu 转载请注明出处

看了网上有人写的,不是很全,而且还有几处错误,所以自己重新找了一下MSDN中的相关内容。


1. cin/wcin

标准C++输入流,有ANSI版本和宽字符版本,用法基本相同,不用多说,下面的例子是cerr,中间也用到了这两个输入函数。

Example
// iostream_cerr.cpp
// compile with: /EHsc
// By default, cerr and clog are the same as cout
#include <iostream>
#include <fstream>

using namespace std;

void TestWide( )
{
   int i = 0;
   wcout << L"Enter a number: ";
   wcin >> i;
   wcerr << L"test for wcerr" << endl;
   wclog << L"test for wclog" << endl;  
}

int main( )
{
   int i = 0;
   cout << "Enter a number: ";
   cin >> i;
   cerr << "test for cerr" << endl;
   clog << "test for clog" << endl;
   TestWide( );
}
Input
3
1
Sample Output
Enter a number: 3
test for cerr
test for clog
Enter a number: 1
test for wcerr
test for wclog

===========================

2. cin.get()

用来读入字符或字符串,可以设置读取的个数和终结字符,而且如下示例可以指定存放的精确位置。注意最后需要留一个位置用来存放'\0'。

Example
// basic_istream_get.cpp
// compile with: /EHsc
#include <iostream>
using namespace std;

int main( )
{
   char c[10];

   c[0] = cin.get( ); //读取一个字符,存入c[0]
   cin.get( c[1] ); //读取一个字符,存入c[1]
   cin.get( &c[2],3 );//读取3个字符,从c[2]开始存放,或遇到'\n'
   cin.get( &c[4], 4, '7' );//读取4个字符,从c[4]开始存放,或遇到'7'

   cout << c << endl;
}
Input
11
Output
11

=============================

3. cin.getline()

从标准输入读取一行,有下面两种重载,没有指定终结符时,实际上默认为'\n'。例子中&c[0]等于直接写c,这样写只是说明可以指定精确存放位置。

basic_istream& getline(
   char_type *_Str,
   streamsize _Count
);
basic_istream& getline(
   char_type *_Str,
   streamsize _Count,
   char_type _Delim
);

Example
// basic_istream_getline.cpp
// compile with: /EHsc
#include <iostream>
using namespace std;

int main( )
{
   char c[10];

   cin.getline( &c[0], 5, '2' );
   cout << c << endl;
}
Input
12
Output
1

==============================

4. getline()

从键盘读取一行,可以不指定终结符,默认为'\n',当然也可以像例子中指定空格。这个是string流,使用时需要包含头文件<string>,注意与前面的cin.getline()区别。

Example
// string_getline_sample.cpp
// compile with: /EHsc
// Illustrates how to use the getline function to read a
// line of text from the keyboard.
//
// Functions:
//
//    getline       Returns a string from the input stream.
//

#pragma warning(disable:4786)
#include <string>
#include <iostream>

using namespace std ;

int main()
{
   string s1;
   cout << "Enter a sentence (use <space> as the delimiter): ";
   getline(cin,s1, ' ');
   cout << "You entered: " << s1 << endl;;
}
Input
test this
Sample Output
Enter a sentence (use <space> as the delimiter): test this
You entered: test

Requirements
Header: <string>

====================

5. gets()/_getws()

从标准输入流读取一行,结尾的换行符'\n'会被替换成'\0'。注意它不检查缓存大小,因此可能造成缓冲区溢出漏洞,尽量少用。

Get a line from the stdin stream.

char *gets(
   char *buffer
);
wchar_t *_getws(
   wchar_t *buffer
);

Example
// crt_gets.c

#include <stdio.h>

int main( void )
{
   char line[21]; // room for 20 chars + '\0'
   gets( line ); // Danger: No way to limit input to 20 chars.
                  // Much preferable: fgets( line, 21, stdin );
                  // but you'd have to remove the trailing '\n'
   printf( "The line entered was: %s\n", line );
}
Input
Hello there!
Output
The line entered was: Hello there!
Note that input longer than 20 characters will overrun the line buffer and almost certainly cause the program to crash.

==================

6.

从终端读取一个字符,有标准和宽字符两者,一组带回显,一组不带。注意返回值是int(或wint_t)

Get a character from the console without echo (_getch, _getchw) or with echo (_getche, _getwche).

int _getch( void );
wint_t _getwch( void );
int _getche( void );
wint_t _getwche( void );

Example
// crt_getch.c
// compile with: /c
/* This program reads characters from
* the keyboard until it receives a 'Y' or 'y'.
*/

#include <conio.h>
#include <ctype.h>

int main( void )
{
   int ch;

   _cputs( "Type 'Y' when finished typing keys: " );
   do
   {
      ch = _getch();
      ch = toupper( ch );
   } while( ch != 'Y' );

   _putch( ch );
   _putch( '\r' );    /* Carriage return */
   _putch( '\n' );    /* Line feed       */
}
Input
abcdey
Output
Type 'Y' when finished typing keys: Y

============================

7.

从流(getc, getwc)或者标准输入(getchar, getwchar)读取一个字符,有标准和宽字符两种版本,返回值也是int(或wint_t)。

Read a character from a stream (getc, getwc), or get a character from stdin (getchar, getwchar).

int getc(
   FILE *stream
);
wint_t getwc(
   FILE *stream
);

int getchar( void );
wint_t getwchar( void );

Example
// crt_getc.c
/* This program uses getchar to read a single line
* of input from stdin, places this input in buffer, then
* terminates the string before printing it to the screen.
*/

#include <stdio.h>

int main( void )
{
   char buffer[81];
   int i, ch;

   /* Read in single line from "stdin": */
   for( i = 0; (i < 80) && ((ch = getchar()) != EOF)
                        && (ch != '\n'); i++ )
      buffer[i] = (char)ch;

   /* Terminate string with null character: */
   buffer[i] = '\0';
   printf( "Input was: %s\n", buffer );
}
Input
This is a test
Output
Input was: This is a test

=============================

8.

从文件流中读取一个字符串,直到遇到换行符,而且换行符也会被读入,并且不会自动转换为'\0';或者读入n-1个字符后自动添加一个'\0',有标准和宽字符两种版本。

Get a string from a stream.

char *fgets(
   char *string,
   int n,
   FILE *stream
);
wchar_t *fgetws(
   wchar_t *string,
   int n,
   FILE *stream
);

Example
// crt_fgets.c
/* This program uses fgets to display
* a line from a file on the screen.
*/

#include <stdio.h>

int main( void )
{
   FILE *stream;
   char line[100];

   if( (stream = fopen( "crt_fgets.txt", "r" )) != NULL )
   {
      if( fgets( line, 100, stream ) == NULL)
         printf( "fgets error\n" );
      else
         printf( "%s", line);
      fclose( stream );
   }
}
Input: crt_fgets.txt
Line one.
Line two.
Output
Line one.

===========================

9.

从流(fgetc, fgetwc)或者标准输入(_fgetchar, _fgetwchar)读取一个字符,有标准和宽字符两种版本。前一组以文件指针作为参数,后一组没有参数。

Read a character from a stream (fgetc, fgetwc) or stdin (_fgetchar, _fgetwchar).

int fgetc(
   FILE *stream
);
wint_t fgetwc(
   FILE *stream
);
int _fgetchar( void );
wint_t _fgetwchar( void );

Example
// crt_fgetc.c
/* This program uses getc to read the first
* 80 input characters (or until the end of input)
* and place them into a string named buffer.
*/

#include <stdio.h>
#include <stdlib.h>

int main( void )
{
   FILE *stream;
   char buffer[81];
   int i, ch;

   /* Open file to read line from: */
   if( (stream = fopen( "crt_fgetc.txt", "r" )) == NULL )
      exit( 0 );

   /* Read in first 80 characters and place them in "buffer": */
   ch = fgetc( stream );
   for( i=0; (i < 80 ) && ( feof( stream ) == 0 ); i++ )
   {
      buffer[i] = (char)ch;
      ch = fgetc( stream );
   }

   /* Add null to end string */
   buffer[i] = '\0';
   printf( "%s\n", buffer );
   fclose( stream );
}
Input: crt_fgetc.txt
Line one.
Line two.
Output
Line one.
Line two.

==============================

10.

C语言继承来的,从标准输入流读取格式化数据,输入格式必须与设置的格式完全相同,示例如下。

Read formatted data from the standard input stream.

int scanf(
   const char *format [,
   argument]...
);
int wscanf(
   const wchar_t *format [,
   argument]...
);

Example
// crt_scanf.c
/* This program uses the scanf and wscanf functions
* to read formatted input.
*/

#include <stdio.h>

int main( void )
{
   int   i, result;
   float fp;
   char c, s[81];
   wchar_t wc, ws[81];
   result = scanf( "%d %f %c %C %80s %80S", &i, &fp, &c, &wc, s, ws );
   printf( "The number of fields input is %d\n", result );
   printf( "The contents are: %d %f %c %C %s %S\n", i, fp, c, wc, s, ws);
   result = wscanf( L"%d %f %hc %lc %80S %80ls", &i, &fp, &c, &wc, s, ws );
   wprintf( L"The number of fields input is %d\n", result );
   wprintf( L"The contents are: %d %f %C %c %hs %s\n", i, fp, c, wc, s, ws);
}
Input
71 98.6 h z Byte characters
36 92.3 y n Wide characters
Output
The number of fields input is 6
The contents are: 71 98.599998 h z Byte characters
The number of fields input is 6
The contents are: 36 92.300003 y n Wide characters

=================

11.

从字符串读取格式化数据,字符串必须已经存在。使用时最好指定字符串宽度,否则,不正常的输入格式容易发生错误。

Read formatted data from a string.

int sscanf(
   const char *buffer,
   const char *format [,
   argument ] ...
);
int swscanf(
   const wchar_t *buffer,
   const wchar_t *format [,
   argument ] ...
);

Example
// crt_sscanf.c
/* This program uses sscanf to read data items
* from a string named tokenstring, then displays them.
*/

#include <stdio.h>

int main( void )
{
   char tokenstring[] = "15 12 14...";
   char s[81];
   char c;
   int   i;
   float fp;

   /* Input various data from tokenstring: */
   sscanf( tokenstring, "%80s", s ); // max 80 character string
   sscanf( tokenstring, "%c", &c );
   sscanf( tokenstring, "%d", &i );
   sscanf( tokenstring, "%f", &fp );

   /* Output the data read */
   printf( "String    = %s\n", s );
   printf( "Character = %c\n", c );
   printf( "Integer: = %d\n", i );
   printf( "Real:     = %f\n", fp );
}
Output
String    = 15
Character = 1
Integer: = 15
Real:     = 15.000000

Security Note: When reading a string with sscanf, always specify a width for the %s format (for example, "32%s" instead of "%s"); otherwise, improperly

formatted input can easily cause a buffer overrun.

=======================

12.

从文件输入流读取格式化数据,输入格式必须与设置的格式完全相同,示例如下。

Read formatted data from a stream.

int fscanf(
   FILE *stream,
   const char *format [,
   argument ]...
);
int fwscanf(
   FILE *stream,
   const wchar_t *format [,
   argument ]...
);

Example
// crt_fscanf.c
/* This program writes formatted
* data to a file. It then uses fscanf to
* read the various data back from the file.
*/

#include <stdio.h>

FILE *stream;

int main( void )
{
   long l;
   float fp;
   char s[81];
   char c;

   stream = fopen( "fscanf.out", "w+" );
   if( stream == NULL )
      printf( "The file fscanf.out was not opened\n" );
   else
   {
      fprintf( stream, "%s %ld %f%c", "a-string",
               65000, 3.14159, 'x' );
      // Security caution!
      // Beware loading data from a file without confirming its size,
      // as it may lead to a buffer overrun situation.
      /* Set pointer to beginning of file: */
      fseek( stream, 0L, SEEK_SET );

      /* Read data back from file: */
      fscanf( stream, "%s", s );
      fscanf( stream, "%ld", &l );

      fscanf( stream, "%f", &fp );
      fscanf( stream, "%c", &c );

      /* Output data read: */
      printf( "%s\n", s );
      printf( "%ld\n", l );
      printf( "%f\n", fp );
      printf( "%c\n", c );

      fclose( stream );
   }
}
Output
a-string
65000
3.141590
x

============the end====================


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值