【转】向字符数组输入空格的方法

方法一

使用gets();(可以使用c和c++混编)

实例:

#include "iostream.h"
#include "stdio.h"
const MAXLENGTH=10;
char s1[MAXLENGTH+1];
main()
{
 cout<<"请输入字符串1"<<endl;
 gets(s1); ###
 cout<<"你输入的字符串一是"<<endl;
 int length1=printf("%s",s1);//可以用来获取输入字符的长度(此处的返回值是打印的字符个数)
 cout<<endl;
 cout<<length1;

}

方法二

使用 cin.getline();

将上面###换为cin.getline(s1,MAXLENGTH+1);即可

关于getline();

Reads a line from the input stream.

msdn 介绍

basic_istream& getline( char_type *_Strstreamsize _Count ); basic_istream& getline( char_type *_Strstreamsize _Countchar_type _Delim );

Parameters

_Count

The number of characters to read from strbuf.

_Delim

The character that should terminate the read if it is encountered before _Count.

_Str

A string in which to write.

Return Value

The stream (*this).

方法三:

使用单个输入

将###处换为

for(int i=0;i<MAXLENGTH+1;i++)

{

scanf("%c",&s1[i]);//此处不可以使用cin

}

上面一些个人观点,如有错误,还请指正,谢谢!!

原文地址:https://www.cnblogs.com/wbb2109/p/2697563.html