简体   繁体   中英

I mixed up two programs in the cs50 sandbox in c?

I mixed up two programs in the cs50 sandbox, one was to find the the number of characters in an array and other was the print these characters. I know the program is garbage but could anyone explain me what is the compiler doing here? When I ran this, the output starts printing alphanumeric text and never stops Thanks

#include <cs50.h>
#include <stdio.h>
#include <string.h>

int main(void)
{

    string s = get_string("Name: ");


    int n = 0;
    while (strlen(s) != '\0')
    {
        n++;
        printf("%c", n);
    }

}

You have multiple problems with the code you show, here's a couple of them:

  • strlen(s) will never be zero as you never modify or remove characters from the string, which means you have an infinite loop
  • n is an integer and not a character so should be printed with the %d format specifier
  • '\\0' is (semantically) a character, representing the string terminator, it's not (semantically) the value 0

To fix the first problem I suspect you want to iterate over every character in the string? Then that could be done with eg

for (int i = 0; i < strlen(s); ++i)
{
    printf("Current character is '%c'\n", s[i]);
}

But if all you want is to could the number of characters in the string, then that's what strlen is already gives you:

printf("The number of characters in the string is %zu\n", strlen(s));

If you want to count the length of the string without using strlen then you need to modify the loop to loop until you hit the terminator:

for (n = 0; s[n] != '\0'; ++n)
{
    // Empty
}

// Here the value of n is the number of characters in the string s

All of this should be easy to figure out by reading any decent beginners book.

while (strlen(s) != '\\0') is wrong. '\\0' equals 0. There string length is never 0, so the loop keeps going on forever, printing integers interpreted as characters.

You can either use the indexes to go through the string characters by using the variable "n" or you can increment the pointer of the string that you have received from the standard input to go through all of its characters.

#include <cs50.h>
#include <stdio.h>
#include <string.h>

int main(void)
{
    string s = get_string("Name: ");

    /* First way using n to iterate */
    int n = 0;
    for (n = 0; n < strlen(s); ++n)
    {
        printf("%c", s[n]);
    }
    printf("\n");

    /* Second way increment the string pointer*/
    while (strlen(s) != '\0')
    {
        printf("%c", *s); //print the value of s
        s++; // go to the next character from s
    }
    printf("\n");

    return 0;
}

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