如何查找字符串的长度

时间:2015-12-08 11:16:52

标签: c++ string string-length

如何使用数据类型“char”找到字符串的长度我尝试了很多次但我没有工作。我也看到了cplusplus教程但无法修复下面的例子

#include <stdio.h>
#include <iostream>
#include<string>

using namespace std;

int main() {
    char str1[80];
    char str2[80];

    cout << "Enter string 1 : ";
    cin.getline(str1,80); cout << endl;
    cout << "Enter string 2 : ";
    cin.getline(str2,80);cout << endl;
    cout << "String 1  is :-> " << (unsigned)strlen(str1) << endl;
    cout << "String 1  is :-> " << (unsigned)strlen(str2) << endl;
}

1 个答案:

答案 0 :(得分:2)

如果您使用的是C ++,我强烈建议您远离char*获取字符串并开始使用std::string

string str1;
string str2;

cout << "Enter string 1 : ";
cin >> str1; cout << endl;
cout << "Enter string 2 : ";
cin >> str2; cout << endl;
cout << "String 1  is :-> " << str1.size() << endl;
cout << "String 2  is :-> " << str2.size() << endl;

PS:您发布的代码适用于我。

相关问题