?
Solved

C Programming, assigning strings to char

Posted on 2010-11-20
7
Medium Priority
?
2,350 Views
Last Modified: 2012-05-10
Hi All,

I had once learned some programming years ago, but almost can't remember how to program anymore. And now I am trying to pick up  c programming again from the begining... and are stuck on how to assigning text to a variable.

Can anyone tell me why I get an error when I run something like the following in a program?  Thanks.

warning: In function ‘main’:
test1.c:57: warning: assignment makes integer from pointer without a cast



void main()
{
     int m;
     char mon;

     m=1;

     if(m==1)
     {
          mon="January";
     }

     printf("Month is:  \n",mon);
}
0
Comment
Question by:wingkchan
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
7 Comments
 
LVL 53

Accepted Solution

by:
Infinity08 earned 600 total points
ID: 34178872
char is a single character.

A string consists of several characters, so either you make it an array of characters :

        char str[16];    /* can hold a string of up to 15 characters */

or you use a pointer to char, and let it point to a string in memory :

        char* str;    /* can point to a string in memory */

For your specific code example, you could do :
int main(void)                /* <--- correct signature of main ! */
{
     int m;
     const char* mon;         /* <--- const char* can safely point to a string literal */

     m=1;

     if(m==1)
     {
          mon="January";
     }

     printf("Month is:  %s\n",mon);    /* <--- the %s is there to actually print the string */

     return 0;                 /* <--- return an int at the end */
}

Open in new window

0
 
LVL 2

Author Comment

by:wingkchan
ID: 34178915
Thanks infinity08 for your quick response... sorry, I am really a novice programming.  when I changed my "char mon[16]" , and then run gcc to compile my program, I get the following messages.

test1.c: In function ‘main’:
test1.c:57: error: incompatible types when assigning to type ‘char[16]’ from type ‘char *’

did i do it wrong?

If you don't mind, let me share my codes with you... it's an assignment of converting the 3 number arguments (year month day), and then outputs them in american date format.  I had worked on it for a day...  although i know the logic and programming flow is very beginner like ...
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>

#define PROGRAM_NAME            "printdate"
#define CORRECT_INPUT_COUNT     4


void main(int argc, char *argv[])
{

        int y;
        int m;
        int d;
        char mon,

/* Check # of input arugments*/

        if(argc != CORRECT_INPUT_COUNT)
        {
                printf("Usage: printdate year month day\n");
                exit(-1);
        }
/* Check year, month, day arguments*/

        if(sscanf(argv[1],"%d", &y)<1)
        {
                printf("Error: year must be a number.\n");
                exit(-2);
        }

        else if(sscanf(argv[2],"%d", &m)<1)
        {
                printf("Error: month must be a number.\n");
                exit(-3);
        }

        else if(sscanf(argv[3],"%d", &d)<1)
        {
                printf("Error:  day must be a number.\n");
                exit(-4);
        }
 else

        if(sscanf(argv[2],"%d", &m)==1)
        {
                mon = "Jan";
        }


                printf("%d-",m );
                printf("%d-",d, ",");
                printf("%d\n",y);

        
                printf("%d-",m );
                printf("%d-",d, ",");
                printf("%d\n",y);

/* Checks for leapyear */     
/*      if(y % 400 == 0)
        {
                printf("Leap Year.\n");
        }
        else if(y % 100 == 0)
        {
                printf("Not Leap Year.\n");
        }
  else if(y % 4 == 0)
        {
                printf("Leap Year.\n");
        }
        else
                printf("Not Leap Year.\n");
*/

Open in new window

0
 

Expert Comment

by:mbseddigh
ID: 34178930
"January" is an array of characters and C compiler holds it as a pointer but mon is a character.
In this assinment Compiler tries to convert a pointer to a character so it shows a warning.
you can use below code:

   
char mon[100] = "September";
    ....
    if (m == 1)
    {
        strcpy (mon, "January");
    }

Open in new window

0
Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 9

Assisted Solution

by:masheik
masheik earned 400 total points
ID: 34179006
Hi, see the following code with comments,


#include <stdio.h>
#include <stdlib.h>
//#include <stdbool.h>

#define PROGRAM_NAME            "printdate"
#define CORRECT_INPUT_COUNT     4


void testmain(int argc, char *argv[])
{

        int y;
        int m;
        int d;
        char mon[15]; //Missed the semicolon here

/* Check # of input arugments*/

        if(argc != CORRECT_INPUT_COUNT)
        {
                printf("Usage: printdate year month day\n");
                exit(-1);
        }
/* Check year, month, day arguments*/

        if(sscanf(argv[1],"%d", &y)<1)
        {
                printf("Error: year must be a number.\n");
                exit(-2);
        }

        else if(sscanf(argv[2],"%d", &m)<1)
        {
                printf("Error: month must be a number.\n");
                exit(-3);
        }

        else if(sscanf(argv[3],"%d", &d)<1)
        {
                printf("Error:  day must be a number.\n");
                exit(-4);
        }
 else

        if(sscanf(argv[2],"%d", &m)==1)
        {
                //mon = "Jan";
			strcpy(mon,"jan");//use string copy strcpy(destination,source)
        }
printf("mon = %s\n",mon);

                printf("%d-",m );
                printf("%d-",d, ",");
                printf("%d\n",y);


                printf("%d-",m );
                printf("%d-",d, ",");
                printf("%d\n",y);

/* Checks for leapyear */
/*      if(y % 400 == 0)
        {
                printf("Leap Year.\n");
        }
        else if(y % 100 == 0)
        {
                printf("Not Leap Year.\n");
        }
  else if(y % 4 == 0)
        {
                printf("Leap Year.\n");
        }
        else
                printf("Not Leap Year.\n");
*/
}

int main(int argc,char *argv[])
{
	testmain(argc,argv);
	getchar();
}

Open in new window

0
 
LVL 53

Expert Comment

by:Infinity08
ID: 34179018
>> test1.c:57: error: incompatible types when assigning to type ‘char[16]’ from type ‘char *’

String assignment doesn't exist in C. You cannot assign a string to another.

What you can do, is assign a pointer to a string to another pointer to a string. Like in the example code I posted in my previous post.


>> 45:            if(sscanf(argv[2],"%d", &m)==1)

sscanf returns the amount of succesfully read tokens. So, if it returns 1 in this case, it means the sscanf succeeded (because it needed to read one %d token, and it did so). So, it's good to check for success in this way.

However, you will still have to check the actual value in m to know which month it is.


In any case :

>> 15:            char mon,

if you change this to be a const char* instead of a char (see the code snippet in my earlier post), it should work better.

Note also that there's a comma at the end of that line, while it should be a semicolon.
0
 
LVL 2

Author Comment

by:wingkchan
ID: 34179227
Thanks all for your input and comments.  especially for the breakdown descriptions.   Actually, i am still unfamiliar with pointers, char syntax.... but nevertheness, with infinity08's code, I did get pass with matching the mon(integer) to text for now... let me keep on writing it.  will return back shortly.  thanks.
0
 
LVL 2

Author Closing Comment

by:wingkchan
ID: 34181423
Thanks again for the input.  Storing the words in pointer solved the problem!  =)
0

Featured Post

What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

An Outlet in Cocoa is a persistent reference to a GUI control; it connects a property (a variable) to a control.  For example, it is common to create an Outlet for the text field GUI control and change the text that appears in this field via that Ou…
This tutorial is posted by Aaron Wojnowski, administrator at SDKExpert.net.  To view more iPhone tutorials, visit www.sdkexpert.net. This is a very simple tutorial on finding the user's current location easily. In this tutorial, you will learn ho…
The goal of this video is to provide viewers with basic examples to understand and use structures in the C programming language.
The goal of this video is to provide viewers with basic examples to understand how to create, access, and change arrays in the C programming language.
Suggested Courses

777 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question