3

I am trying to become less dependent on the cs50.h library. I have tried different combinations to replace this line string input = GetString(); but I can't get anything working. Compiler keeps telling me there's something wrong with the pointer operators * or &. I know string means char*, but I can't figure GetString() out.

How can I write that line with pure C?

1
  • I think you've had this question answered in the Facebook group? – curiouskiwi Nov 1 '16 at 0:45
2

If you know in advance how big of a string you are willing to accept, you can put the limit into your scanf argument itself. Try this small program:

#include <stdio.h>
int main(void)
{
    char words[15];
    scanf("%14s", words); 
    printf("%s\n", words);
}

You're telling scanf to only take in 14 characters (with the 15th reserved for the null char at the end that scanf adds). This works with no memory problems.

1
1

Funny thing is that I can't get much to work right in cs50.h so I've just been looking up standard c programming techniques. It's just been much easier to find working examples on the Internet using standard c without cs50.h. for the life of me I can't get get_string() in cs50.h working even though I copied the example in the manual.

This link has 3 great samples for string input and output https://www.programiz.com/c-programming/c-strings

The scanf() in example 1 doesn't support spaces. Example 2 uses getchar() and I like this version for learning because it forces you to go through the process of capturing every letter. I've been helping my young son learn this.

Example 3 uses gets() but that is an extremely dangerous function. It produces code that is extremely likely to be exploited. Make will even warn you about it even though it will compile.

The function that was recommended by an elite programmer was fgets(). Here's a great example of how to use it. https://www.w3resource.com/c-programming-exercises/string/c-string-exercise-4.php

3
  • What errors/unexpected behaviours do you get when using get_string? It is a beautifully crafted artwork that really does make it easier to learn C. – Christopher Flores Apr 13 '18 at 15:33
  • I got it to work if I manually link cs50.h with GCC but the default makefile for make doesn't work. – George Ou Apr 15 '18 at 4:11
  • Ahh. What's happening is that cs50's IDE/appliance has some special enviroment variables set that automatically link the cs50 library, as well as some flags that tell the compiler to treat warnings (bad) as errors (worse), sanitise integer overflow, and to keep data necessary for the debugger to work. CFLAGS=-fsanitize=signed-integer-overflow -fsanitize=undefined -ggdb3 -O0 -std=c11 -Wall -Werror -Wextra -Wno-sign-compare -Wshadow and LDLIBS=-lcrypt -lcs50 -lm – Christopher Flores Apr 15 '18 at 9:53

You must log in to answer this question.

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