0. 前言
包含头文件
#include<iostream>
#include<string>
1. char cstr[100] 和 cin
int main() {
char cstr[100];
cin >> cstr;
int n = strlen(cstr);
cout << "strlen(cstr) = " << n << endl;
return 0;
}
输入:
hello world
输出:
strlen(cstr) = 5 //cin只读入了"hello"
2. char cstr[100] 和 getline
int main() {
char cstr[100];
cin.getline(cstr, 100);
int n = strlen(cstr);
cout << "strlen(cstr) = " << n << endl;
return 0;
}
输入:
hello world
输出:
strlen(cstr) = 11
3. char *cstr = “…” 和 strlen
int main() {
char *cstr = "hello world";
int n = strlen(cstr);
cout << "strlen(cstr) = " << n << endl;
return 0;
}
输出:
strlen(cstr) = 11
4. char *cstr = {…} 和 strlen
int main() {
char *cstr = {'h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd'};
int n = strlen(cstr);
cout << "strlen(cstr) = " << n << endl;
return 0;
}
编译报错:
[Error] scalar object 'cstr' requires one element in initializer
5. char cstr[100] = “…” 和 strlen
int main() {
char cstr[100] = "hello world";
int n = strlen(cstr);
cout << "strlen(cstr) = " << n << endl;
return 0;
}
输出:
strlen(cstr) = 11
6. char cstr[100] = {…} 和 strlen
int main() {
char cstr[100] = {'h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd'};
int n = strlen(cstr);
cout << "strlen(cstr) = " << n << endl;
return 0;
}
输出:
strlen(cstr) = 11
7. string str 和 cin
int main() {
string str;
cin >> str;
int n = str.length();
cout << "str.length() = " << n << endl;
return 0;
}
输入:
hello world
输出:
str.length() = 5
8. string str 和 getline
int main() {
string str;
getline(cin, str);
int n = str.length();
cout << "str.length() = " << n << endl;
return 0;
}
输入:
hello world
输出:
str.length() = 11