1
string reading_lev(int a, int b, int c)
{
    float L = (a / b) * 100;
    float S = (c / b) * 100;
    float index = 0.0588 * L - 0.296 * S - 15.8;
    if (round(index) <= 16 && round(index) >= 1)
    {
        string val = printf("Grade %f", index);
    }
    else if (round(index) > 16)
    {
        string val = printf("Grade 16+");
    }
    else
    {
        string val = printf("Before Grade 1");
    }
    return val
}

The error is in the first if block. There are cs50 libraries involved.

error: incompatible integer to pointer conversion initializing 'string' (aka 'char *') with an expression of type 'int' [-Werror,-Wint-conversion]

2 Answers2

4

The error message is self explanatory.

printf() returns an int, you cannot assign it to variable of type char*.

That said, you have multiple other issues:

  • The return statement uses a block scope variable, which is out of it's scope.
  • The return statement is missing a ; - syntax error.

To fix the code what you need to do is:

  • Allocate a buffer long enough to hold the final output. (Define a pointer and use allocated memory using malloc() or family, of sufficient size)
  • Use sprintf() to populate the memory with the output you need.
  • Return the pointer.
  • Once you're done using it, free() the returned pointer.
Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
  • I'm sorry if this is really basic but I am new. How can printf() return an int? Isn't everything in " "? – Kushagra Sharma Apr 08 '20 at 20:10
  • 2
    @KushagraSharma Read the linked man page.What printf prints and what is returns are not the same. – Sourav Ghosh Apr 08 '20 at 20:11
  • @kaylum Updated. – Sourav Ghosh Apr 08 '20 at 20:11
  • 1
    @KushagraSharma One of the first things you need to do as a C programmer is find the documentation. On unix systems, you can open a terminal window and type `man 3 printf` to get the documentation for `printf`. On windows, the documentation is online by searching `msdn printf`. You might also want to invest in a [good reference book](https://stackoverflow.com/questions/562303/the-definitive-c-book-guide-and-list). – user3386109 Apr 08 '20 at 20:14
  • @user3386109 Its 2 in the morning where I live X( could you please briefly tell me how to fix my code? It would really help me. – Kushagra Sharma Apr 08 '20 at 20:23
1

You can use sprintf to save the formatted data to a string. Be aware that you need a buffer big enough to save the string.

http://www.cplusplus.com/reference/cstdio/sprintf/

cmp
  • 35
  • 6