0
点赞
收藏
分享

微信扫一扫

C/C++语言中字符串输入详解

尤克乔乔 2022-01-26 阅读 73


C/C++语言中字符串输入详解【updating…】

1.字符串

字符串处理 是 编程语言中十分常见的操作,在C++语言中也不例外,下面给出C/C++语言中对字符串的处理。

2.字符串处理

2.1 字符串的输入
  • 使用​​scanf()​​​函数
    使用如下程序,可以定义一个字符串,并输入这个字符串。
#include<cstdio>
#include<string>
#include<cstring>
#include<iostream>

using namespace std;
int main(){
char str[101];
scanf("%s",&str);
printf("%s",str);
}

例如,输入 ​​hello​​时 ,返回​​hello​​。执行结果如下:

C/C++语言中字符串输入详解_ios

假设我们输入的是​​hello world​​,却得到如下结果:

C/C++语言中字符串输入详解_ios_02

这个时候,我们就有点儿懵了,为什么这里得到的结果是​​hello​​,我们明明输入的是​​hello world​​啊!!

这是因为​​C语言​​中使用​​scanf()​​函数时,是以空格为分隔符的,导致出现只将空格前的一部分【​​hello​​】作为了输入;而后一部分​​world​​却直接忽略了。

  • 使用​​gets()​​​函数
    那么如何解决这个问题呢?修改程序如下:
#include<cstdio>
#include<string>
#include<cstring>
#include<algorithm>
#include<iostream>

using namespace std;
int main(){
char str[101];
gets(str);

printf("%s",str);
}

得到的执行结果就是如下的样子:

C/C++语言中字符串输入详解_#include_03

虽然​​gets()​​函数很好用,但是坊间存在它的很多恐怖传说,而且在​​gcc 14​​的编译器中,已经不再支持它的使用了。所以使用它也不是一个很好的方式。

  • 使用​​getline()​​函数
#include<cstdio>
#include<string>
#include<cstring>
#include<iostream>

using namespace std;

int main() {
char a[20];

for(int i=0;i<20;i++){
a[i]='\0';
}
cin.getline(a,20);
cout << a<<endl;

for(int i=sizeof(a)-1;i>=0;i--)
{
if(a[i]!='\0') cout<<a[i];
}
return 0;
}

执行结果如下:

C/C++语言中字符串输入详解_#include_04

2.2 字符串的比较

习惯了 ​​java​​ 编程的同志可能会写出如下的代码:

char d[10];
getchar();
scanf("%s",&d);
if( d== "lawson") cout<< "lawson"<<endl;
else cout<<"other"<<endl;

但是上述的代码在C/C++中是不会生效的。因为这是错误的代码。不能使用char数组和字符串直接比较。但是可以将​​char d[10]​​替换成一个string类型变量。如下:

#include<cstdio>
#include<iostream>
#include<string>

using namespace std;

int main(){
string s1 ;
string s2 = "lawson";
cin >> s1;
if(s1 == s2){
cout << "s1 = s2" << endl;
} else{
cout << "s1 != s2"<< endl;
}
}

得到的执行结果如下:

C/C++语言中字符串输入详解_字符串_05

== update on 20200104 ==


  • 字符串之间的比较操作:
  • 字符串的​​length()​​函数的使用

[root@localhost ecnu]# cat test5.cpp 
#include<cstdio>
#include<iostream>
#include<algorithm>
#include<cstring>

using namespace std;

int main(){
string str = "sdfs";
cout <<"str的长度是:"<< str.length()<<endl;
cout <<"str[3]= " <<str[3]<<endl;

string a = "1231";
string b = "123";
string c = "2";
if(a<b) cout << "a<b"<<endl;
if(a>b) cout << "a>b"<<endl;
if(b>c) cout << "b>c"<<endl;
if(b<c) cout << "b<c"<<endl;
}

执行结果如下:

[root@localhost ecnu]# ./test5
str的长度是:4
str[3]= s
a>b
b<c



举报

相关推荐

0 条评论