0

I am trying to use a string variable after having included the header file stdio.h but for some reason it is not working. The color of the word "string" does not change as opposed to int, float, double etc. When I ignored this and went ahead to compile my program, it prompted an error regarding the string variable.

3 Answers 3

1

The type string is not a native type in C. It's defined by the CS50 library which you can use by #includeing the cs50.h header file and linking the library's binary file with -lcs50.

The actual type that the CS50 library defines as string is char *. So using char * (without using the CS50 library) is equivalent to using string when using the CS50 library.

1

You don't even need to use string.h header file if you don't need to use string specific functions. Try to use following to figure it out by yourself:

#include <stdio.h>

int main(void)
{
    char greeting[] = "Hello";
    printf("%s", greeting);

}

You need to play bit more in C with strings. E.g. you can't initialize array of characters (string in C) without specification of size. Either you need to specify size like this:

char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0');

or like in first example (probably C compiler will do it for you):

char greeting[] = "Hello";
0
0

Indeed, the color of string doesn't change, but it is defined in the cs50 header/library. The problem might be that you didn't #include <cs50.h>, or that there is some other error.

This is my code:

#include <stdio.h>
#include <cs50.h>
int main(void)
{
    string str = get_string("What's your name? ");
    printf("Hello %s!\n", str);
}

This is the result: Terminal

Computer: What's your name?

My input: something

Computer: Hello something!

This shows that using the CS50 header's data type (string) works and you may have an error somewhere else in your code.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .