简体   繁体   中英

Counting the Whole String Including The Spaces in C

I'm trying to set up a code that counts the whole string and doesn't stop after the first space that it finds. How do I do that?

I tried this kind of code but it just counts the first word then goes to display the number of letters in that first word.

So far this is what I have tried.

int main(){
    char get[100];
    int i, space=0, len=0, tot;
    scanf("%s", get);

    for (i=0; get[i]!='\0'; i++)
    {
        if (get[i] == ' ')
            space++;
        else 
            len++;
    }

tot = space + len;
printf("%i", tot);
}

And

int main(){
    char get[100];
    int len;
    scanf("%s", &get);
    len = strlen(get);
    printf("%i", len);
}

But would still get the same answer as the first one.

I expected that if the input: The fox is gorgeous. output: 19

But all I get is input: The fox is gorgeous. output: 3

strlen already includes spaces, since it counts the length of the string up to the terminating NUL character (zero, '\\0' ).

Your problem is that that the %s conversion of scanf stops reading when it encounters whitespace, so your string never included it in the first place (you can verify this easily by printing out the string). (You could fix it by using different scanf conversions, but in general it's easier to get things right by reading with fgets – it also forces you to specify the buffer size, fixing the potential buffer overflow in your current code.)

The Answer by Arkku is correct in its diagnose. However, if you wish to use scanf, you could do this:

scanf("%99[^\n]", get);

The 99 tells scanf not to read more than 99 characters, so your get buffer won't overflow. The [^\\n] tells scanf to read any character until it encounters the newline character (when you hit enter).

As Chux pointed out, the code still has 2 issues.

When using scanf, it is always a good idea to check its return value, which is the number of items it could read. Also, indeed the \\n remains in the input buffer when using the above syntax. So, you could do this:

if(scanf("%99[^\n]", get) == 0){
    get[0] = 0; //Put in a NUL terminator if scanf read nothing
}

getchar();      //Remove the newline character from the input buffer

I will take one example to explain the concept.

main()
{
  char s[20], i;

  scanf("%[^\n]", &s);
    while(s[i] != '\0') {
       i++;
   }
  printf("%d", i);

  return 0;
}

i have used c language and u can loop through the ending the part of the string and you will get the length. here i have used "EDIT SET CONVESRION METHOD" to read string, you can also gets to read.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM