C转C++(1)

1.I/O

C语言中使用<stdio.h>中的scanf和printf来输入输出,需要使用标识符,如“&d"等等,略显麻烦。

而C++中的<iostream>中的cin和cout 会自动识别数据类型,使得输入输出更加简单。

#include<iostream>
using namespace std;
int main(){
    int n;
    cin>>n;
    cout<<"helloworld"<<endl<<++n<<endl;
    return 0;
}

using namespace std; 是C++中的一个语句,它表示在当前代码文件中使用命名空间 std 中的所有内容,而不需要在每个标识符前都加上 std:: 前缀。

C++的标准库中的各种类、函数、对象等都被放置在 std 命名空间中,为了使用这些标准库中的功能,你可以在代码文件的开头使用 using namespace std;,这样就不需要在每次使用标准库的元素时都写上 std:: 前缀。

endl就是C语言的”\n“换行符。

2.string类

C++与C语言一样拥有字符串即字符数组,不过strcpy等函数放在了<cstring>的库里面,这种字符串被称为”C语言风格的字符串“。

#include<iostream>
#include<cstring>
using namespace std;
int main(){
    char s[6]="chemy";
    char s1[6],s2[20]="math";
    strcpy(s1,s);
    strcat(s2,s1);
    cout<<s1<<endl<<s2<<endl<<strlen(s2);
    return 0;
}

C++ 标准库提供了 string 类类型,支持上述所有的操作,另外还增加了其他更多的功能。

#include<iostream>
#include<cstring>
using namespace std;
int main(){
    string s="chemy";
    string s1=s,s2="math";
    cout<<s1<<endl;
    s1=s+s2;
    cout<<s1<<s.length()<<endl;
    return 0;
    
}

字符串可以直接赋值了,甚至还可以直接进行加法(拼接)

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值