c++如何输入带空格的字符串

1、scanf函数(包含头文件#include <stdio.h>)

   scanf函数一般格式为scanf(“%s”,st),但scanf默认回车和空格是输入不同组之间的间隔和结束符号,所以输入带空格,tab或者回车的字符串是不可以的。解决方法如下: 1)利用格式符“%[]”它的作用为扫描字符集合。Scanf(“%[^c]”,str); 其中“c”是一个具体的字符常量(包括控制字符)。当输入字符串时,字符“c”将被当作当前输入的结束符。利用此格式符就可以由编程者自己指定一个输入结束符。例如:scanf("%[a-z A-Z0-9]",str)表示只匹配输入是大小写字母和数字,遇到非数字和字母时输入结束。

例如:

#include<cstdio>
using namespace std;

int main()
{
    char s[55];
    scanf("%[^\n]",s);
    printf("%s",s);
    return 0;
}

2. cin(包含头文件#include <iostream>)

cin是C++中最常用的输入语句,当遇到空格或者回车键即停止。无法解决。

3. gets()

可以无限读取,以回车结束读取,C语言中的函数,在C++中运行会产生bug。在C11标准中已被正式删除,建议不要用!!!

#include<cstdio>
using namespace std;

int main()
{
    char s[55];
    gets(s);
    printf("%s",s);
    return 0;
}

4. getline()(包含头文件#include <string>)

若定义变量为string类型,注意不是字符型数组。则要考虑getline()函数。用法如下:

#include<iostream>
#include<string>
using namespace std;

int main()
{
    string s;
    getline(cin,s);
    cout<<s<<endl;
    return 0;
}

4.cin.get (char *str, int maxnum)

cin.get()函数可以接收空格,遇回车结束输入

#include<iostream>
#include<string>
#include<cstring>
using namespace std;

int main()
{
    char s[50];
    cin.get(s, 50);
    printf("%s",s);//也可以用cout<<s;
    return 0;
}

5.cin.getline (char *str, int maxnum)(包含头文件#include <string>)

cin.getline()函数可以同cin.get()函数类似,也可接收空格,遇回车结束输入。

#include<iostream>
#include<string>
#include<cstring>
using namespace std;

int main()
{
    char s[50];
    cin.getline(s, 50);
    printf("%s",s);//也可以用cout<<s;
    return 0;
}

6. 字符串类型转换为字符数组

#include<iostream>
#include<string>
#include<cstring>
using namespace std;

int main()
{
    char s[50];

    string s1 = "hello world!";
    strcpy(s, s1.c_str());

    printf("%s\n",s);//也可以用cout<<s<<endl;

    string s2 = "I love you!";
    strcpy(s, s2.data());
    printf("%s\n",s);//也可以用cout<<s<<endl;

    return 0;
}

原文地址:C++如何输入含空格的字符串 - Tomorrow1126 - 博客园 (cnblogs.com)

  • 6
    点赞
  • 29
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值