C/C++ 输入带空格的字符串

机试的时候碰到的问题,当时脑子卡克到想不出来怎么处理,用了一种贼复杂的方法,,现在整理下!

 

C语言

 方法1

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

int main()
{
    char s[100];
    gets(s);

    printf("%s",s);
    return 0;
}

一句gets解决的事情,我居然tm没想起来。。。。太羞耻了

gets读取一行,遇到\n结束,它会把\n一并读取,并将\n替换为\0   (\n不会留在缓冲区) 

 

方法2

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

int main()
{
    char s[100];
    //scanf("%*c"); 如果前面有输入过,则用它来吸收最后的\n

    int i=0;
    while(scanf("%c",&s[i]),s[i]!='\n')
        i++;

    s[i]='\0';
    printf("%s",s);
    return 0;
}

每接收一个字符并存入,读到\n结束

 

方法3

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

int main()
{
    char s[100];
    fgets(s,40,stdin);

    printf("%s",s);
    return 0;
}

和gets差不多,fgets会读取行尾的\n,然后再添加\0 最后是 xxxx\n\0  (\n不会留在缓冲区)

 

 

C++

方法1

#include <iostream>
using namespace std;

string s;

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

需要包含头文件#include<string>

如果需要转化为char*,在C++中string封装了字符串的操作,总结一下,把string转化为字符数组或指针有一下三种方式:

//(1)c_str()

      string str="hi,girls!";
      char *p=str.c_str();


//(2)data()

      string str="hello";
      char *p=str.data();


//(3)copy(p,len,start)

    string str="howareyou";
     char pStr[40];
     str.copy(pStr,7,0); //7代表复制几个字符,0代表复制的位置
     *(pStr+7)='\0';     //手动加上结束符

 

方法2

#include <iostream>
using namespace std;

const int N = 20;
char x[N+1];

int main(){
	cin.getline (x,N+1); //这里最好写N+1,因为字符串末尾的的'\0'也包含在这个长度之内.
	cout<<x<<endl;
	printf ("%s\n",x);
	return 0;
}

需要包含头文件#include<iostream>

 

 

参考文献:

https://blog.csdn.net/cool_oyty/article/details/7738703

https://blog.csdn.net/qq_34600424/article/details/79432947

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值