我想知道为什么反转1那个代码没有报错但是运行不了。
源代码如下:
#include<bits/stdc++.h>
using namespace std;
int main(){
cout<<"hello world"<<endl;
cout<<"hello world"<<'\n';
printf("hello world");
/*在全局定义的数组才能初始化为0,如果是在函数内部定义的数组
则数组不能初始化为0*/
char s[] = "hello";
cout<<'\n';
for(int i = 0;i <= 4;++i){
cout<<s[i];
}
cout<<'\n';
cout<<s<<'\n'; //输出s(遇到\0就停下)并换行
//利用c.str()将输入的字符串转换成字符输出
char buf[100];// 临时变量,用于输入
scanf("%s",buf); //输入buf
string str(buf);//用buf来构造str
printf("str = %s\n",str.c_str());//输出str
//获取字符串的长度
string str0 = "hello, world!" ;
int length = str0.length();
cout<<"length:"<<length<<endl;
//拼接字符串
string str1 = "hello";
string str2 = "world!";
//方法一,用+号连接
string result1 = str1 + "," + str2;
//方法二,用append
string result2 = str1.append(",").append(str2);
cout<<"result1"<<result1<<endl;
cout<<"result2"<<result1<<endl;
//字符串的查找
string str3 = "hello, world!";
int pos1 = str3.find("hello");
int pos2 = str3.find("helllo");
cout<<"substring found at position"<<pos1<<endl;
cout<<"substring found at position"<<pos2<<endl;
//字符串的替换
string str4 = "hello, world!";
str4.replace(7,5,"university");
cout<<"reslut:"<<str4<<endl;
//提取字符串
string str5 = "hello, world";
string subStr = str5.substr(7,5);
cout<<"subString:"<<subStr<<endl;
//字符串的比较
string str6 = "hello";
string str7 = "world";
int result = str6.compare(str7);
if(result == 0){
cout<<"string are equal."<<endl;
}
else if(result < 0){
cout<<"string 6 is less than string 7.";
}
else{
cout<<"string 6 is greater than string 7.";
}
//遍历string的方法
string s0 = "hello";
//(1)循环枚举下标
for(int i = 0;i < s0.length();++i)
cout<<s0[i];
cout<<'\n';
//(2)auto枚举(其中&表示引用类型,如果对i修改将会改变原来的值)
for(auto i:s0){
cout<<i;
i = 'a';
}
cout<<'\n';
cout<<s0<<'\n'; //hello
cout<<'\n';
for(auto &i : s0){
cout<<i;
i = 'a';
}
cout<<'\n';
cout<<s0<<'\n'; //aaaaa
//反转1
string s1;
cout<<"please enter a s1:"<<'\n';
getline(cin,s1);
for(int i = (int)s1.length()-1;i >= 0;--i){
cout<<s1[i]<<'\n';
}
//反转2
string s2;
cout<<"please enter a s2:"<<'\n';
getline(cin,s2);
reverse(s2.begin(),s2.end());
cout<<s2<<'\n';
return 0;
}
运行结果如下:

