-
Macro confusion
Thought these things would be simple, but apparently I don't understand them. All I want to do is have an input of a message, and the macro picks it up and prints it until you close the window. What needs to change, or am I way off in left field with this one?
Code:
#include <stdio.h>
#define ECHO (str) gets (message);\
for (i=0; i != NULL; ++i)\
puts(message);
int main ()
{
int i;
i=0;
printf("Enter a message:");
Echo (str);
return 0;
}
-
Code:
#include <stdio.h>
#define ECHO (str) gets (message);\
for (i=0; message[i] != NULL; ++i)\
putchar(message[i]);
int main ()
{
int i;
i=0;
printf("Enter a message:");
Echo (str);
return 0;
}
I think that was your intent. Code's pretty funky, but, I think it'll work.
-
Now the error message is that Echo is undefined. That makes no sense to me since right before Echo is the word define. What gives?
-
Case sensitive
Code:
#include <stdio.h>
#define ECHO (str) gets (message);\
for (i=0; message[i] != NULL; ++i)\
putchar(message[i]);
int main ()
{
int i;
i=0;
printf("Enter a message:");
ECHO(str);
return 0;
}
-
That pretty well sums it up. Thanks for helping this lowly noob.
-
Also you should remove space between ECHO and (
I doubt it will work because message is undefined, str is undefined (not not used by the macro, why do you need it?)
Don't use gets - use fgets (see FAQ)
-
this will do what u want.
Code:
#include <stdio.h>
#define ECHO(message) fgets(message,80,stdin);\
fflush(stdout);\
fputs(message,stdout);
int main ()
{
int i=0;
char str[80];
printf("Enter a message:");
ECHO(str);
getchar();
return 0;
}
/*my output
Enter a message:hello there
hello there
*/
ssharish2005
-
> What needs to change, or am I way off in left field with this one?
Like you should be using a function if you possibly can, not an inline macro.
Consider the mess you get into by doing say
if ( condition ) ECHO(message);
-
Multiline macros can be done quite well when using a do ... while(0) construct. Of course one should use functions an let the compiler decide ;)