Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Get string lenght in C

I want to loop all the characters in a string to get the string lenght but it is not working. I prefer not using an already made function to do so.

#include <stdio.h>
#define N 100
int main()
{
    int i=0;
    char str[N];
    scanf("%s", &str);
    while(str[i]!="\0"){
        i=i+1;
    }
    printf("Lenght: %d", i);
    return 0;
}

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

For starters the call of scanf must look at least like

scanf("%s", str);

instead of

scanf("%s", &str);

In the condition of the while loop

while(str[i]!="\0"){

there is compared a characters with the string literal "\0" that is implicitly converted to a pointer to its first character. So there is compared a character with a pointer.

You need to compare two characters

while(str[i] != '\0' ){

or just

while(str[i]){
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading