for
#include <iostream>
using namespace std;
int main() {
char str[100] = { 0 };
cin.getline(str, sizeof(str));
// write your code here......
char* ptr = str;
int len = sizeof(str) / sizeof(char);
int length = 0;
for (int i=0; i<len; i++) {
if (*ptr != NULL)
length += 1;
ptr++;
}
cout << length << endl;
return 0;
}
while
#include <iostream>
using namespace std;
int main() {
char str[100] = { 0 };
cin.getline(str, sizeof(str));
// write your code here......
char* ptr = str;
int len = sizeof(str) / sizeof(char);
int length = 0;
while (*ptr != NULL) {
length += 1; // length++;
ptr++;
}
cout << length << endl;
return 0;
}
或者:
见详解:
https://www.nowcoder.com/practice/9a2d212d23f5436c80607d5e68c6d12a?tpId=225&tags=&title=&difficulty=0&judgeStatus=0&rp=0
#include <iostream>
using namespace std;
int main() {
char str[100] = { 0 };
cin.getline(str, sizeof(str));
// write your code here......
char* ptr = str;
int length = 0;
//只要指针没有指向换行符位置
while (*ptr != '\0') { // 换行符是 '\0',不能写"\0"
//长度加1,指针p后移
length++; // length += 1;
ptr++;
}
cout << length << endl;
return 0;
}