Home > Blockchain >  C char array compare ' ' and '\0' and counter doesn't work
C char array compare ' ' and '\0' and counter doesn't work

Time:07-30

I'm new to C . I have a simple practice function I try to count how many words in a full name, first I pass a char array fullName to nameCount function with a counter then it will compare each char in the array with ' 'and '\0' if it meet any of these 2 chars, counter will 1. But I don't know why the counter give back a very large number. Please help me out with the code. Thanks a lot.

#include <iostream>
    
using namespace std;
   
    
void nameCount (char[],int&);
    
const int LENGTH =30;
int main()
{
    char name[LENGTH];
    int count=0;
    cout<<"Input full name: ";
    cin.getline(name, LENGTH);
    nameCount(name, count);
    cout<<count;
    return 0;
}

void nameCount(char fullName[],int& count) {
    
    for(int i=0; i<LENGTH;i  ){
        if (fullName[i]==' ' || fullName[i]=='\0')
            count  ;
    } 
}

Example & Result:

  1. Input Full Name:John Smith

0

CodePudding user response:

You have the common newbie confusion between parameters and return values.

When you want a function to calculate something you return that value from the function, You don't pass the variable as a parameter.

Here's how your code should look

int nameCount(char fullName[]) {
    int count = 0;
    for (int i = 0; i < LENGTH; i  ) {
        if (fullName[i] == ' ' || fullName[i] == '\0')
            count  ;
    }
    return count;
}

and here's how you call the function

int count = nameCount("John Smith");

Even with that improvement there appear to be bugs in your code. I would suggest this as an improvement

int nameCount(char fullName[]) {
    int count = 0;
    for (int i = 0; fullName[i] != '\0'; i  ) {
        if (fullName[i] == ' ')
            count  ;
    }
    return count;
}

However since I can't see the rest of your code this might not be right.

EDIT

So full source code is now available (thanks).

Here's a fully working main

#include <iostream>
    
using namespace std;
   
    
int nameCount (char[]);
    
const int LENGTH =30;
int main()
{
    char name[LENGTH];
    cout<<"Input full name: ";
    cin.getline(name, LENGTH);
    cout << name_count(name) << '\n';
    return 0;
}

And as stated your function actually counts spaces not words, so nameCount("John Smith") returns one not two, but that's a different problem.

  • Related