-2

This is a program to find the longest word in a string but i have a problem.the compiler said that i cant compare a pointer to integer!but i compare a char pointer to a char in line

#include <string.h>
#include <string>
#include <iostream>
using namespace std;

string longest(char * a)
{
    int count=0;
    int finalcount=0;
    string longs="";
    string longest;  
    int lena=strlen(a);
    for(int i=0;i<lena;i++)
    {
        if(*a==" ")
        {
            if(count>=finalcount)   
            {
                finalcount=count;
                longest=longs;
            }
            count=0;
            longs="";
        }
        else{*a++;count++;longs+=*a;}
    }
    return longest;
}
int main()
{
    char a[]="which is the longest";
    cout<<longest(a);
    return 0;
}
herohuyongtao
  • 49,413
  • 29
  • 133
  • 174

2 Answers2

7

*a is a char here, so you should compare it to another char (instead of a string literal with type const char *) by using ==.

You need to change

if(*a==" ")

to

if(*a==' ')
Community
  • 1
  • 1
herohuyongtao
  • 49,413
  • 29
  • 133
  • 174
0

I agree with the answer of herohuyongao. But I think it is only the smallest fix to your error. This code will be still "C style". In C++ you should prefer std::string to char *

So your code should be like this:

#include <string>
#include <iostream>

using namespace std;

string longest(string a) {
    int count = 0;
    int finalcount = 0;
    string longs = "";
    string longest;
    int lena = a.length();
    for (int i = 0; i < lena; i++) {
        char c = a[i];
        if (c == ' ') {
            if (count >= finalcount) {
                finalcount = count;
                longest = longs;
            }
            count = 0;
            longs = "";
        } else {
            count++;
            longs += c;
        }

    }
    if (count >= finalcount) {
        finalcount = count;
        longest = longs;
    }
    return longest;
}

int main() {
    string a = "which is the longest";
    cout << longest(a);
    return 0;
}
Issam T.
  • 1,677
  • 1
  • 14
  • 32