【问题标题】:how to find the length of the string on the array?如何找到数组中字符串的长度?
【发布时间】:2020-02-23 11:04:33
【问题描述】:

我正在尝试从 char 数组中获取字符串的长度

我的输入是:alpha kian namikian,输出应该是 5 4 8,但目前我的输出是 11 11 11 11 11 11 11 11 11 11 11,这不是我想要实现的目标。

int i,count;
char str[100];  
cout<<"enter string\n";
for(i=0;;i++)
{
    cin>>str[i];

    if(cin.get()=='\n')
    {
        count=i+1;
        break;
    }
}
for(i=0;i<count;i++)
{
    int len = strlen(str);
    cout<<len<<"\n";
}

【问题讨论】:

  • 尝试在数组中使用字符而不是字符串。
  • 好吧我试着改变
  • 例如:“string”是一个字符数组。
  • 好的,所以我调整了它,但是当我尝试这个输入时结果输出不正确:alpha kian namikian output: 11 11 11 11 11 11 11 11 11 11 11

标签: c++ arrays string strlen


【解决方案1】:

您遇到了编译错误,因为您试图将字符串数组作为strlen 的参数。在您的代码中,str 包含所有字符串,因此您必须使用访问运算符 [],就像您从标准输入中获取字符串时一样。

int len = strlen(str) 变为 int len = strlen(str[i]) 应该可以修复错误。

编辑:

您似乎不能将strlen 与字符串一起使用。请改用length()

int len = str[i].length()

编辑#2:

添加完整代码以供输出参考:

#include <iostream>
#include <string>

using namespace std;

int main()
{
    int i, count;
    string str[100];
    cout << "enter string\n";
    for (i = 0;; i++)
    {
        cin >> str[i];

        if (cin.get() == '\n')
        {
            count = i + 1;
            break;
        }
    }
    for (i = 0; i < count; i++)
    {
        int len = str[i].length();
        cout << len << "\n";
    }
}

输出:

输入字符串

阿尔法基安纳米基安

5

4

8

【讨论】:

  • 所以我尝试更改它,但结果是 [错误] 从 'char' 到 'const char*' 的无效转换 [-fpermissive]
  • int i,count,len;字符 str[100]; cout>str[i]; if(cin.get()=='\n') { count=i+1;休息; } } for(i=0;i
  • 对不起,我不知道如何正确地写下这段代码,就像我的帖子一样,我是新的,对不起
  • 看看我的编辑,你实际上不能用字符串使用strlen() - 你必须使用length()
  • 可以通过“sizeof str/ sizeof str[i]”为您提供没有循环的长度
【解决方案2】:

您可以使用vector 类型string 使用此方法,如果输入的字符串为exit,则退出字符串的存储
我正在使用temp 变量将字符串存储在任何索引处并输出相应的长度。

    int i;
    vector<string> str;
    cout << "Enter String\n";
    while(cin)
    {
        string temp;
        cin >> temp;
        if(temp == "exit")
            break;
        else
            str.push_back(temp);

    }
    int n= str.size();
    for(i = 0; i< n; i++)
    {
        string temp = str[i];
        int len = temp.length();
        cout << len << endl;
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-12-28
    • 1970-01-01
    • 2012-06-23
    • 1970-01-01
    • 2013-01-12
    • 2018-01-20
    相关资源
    最近更新 更多