I'm trying to use putchar() and getchar() to read in a string of characters from the user, and then my loop will print each character three times, print a new line, etc etc, until every character in the variable "userInput" has been printed. When I try to compile my program I receive the following errors:
warning: assignment makes pointer from integer without a cast [enabled by default]
userInput = getchar();
^
warning: comparison between pointer and integer [enabled by default]
while(counter < strlen(userInput))
^
error: array subscript is not an integer
putchar(userInput[counter]);
^
error: array subscript is not an integer
putchar(userInput[counter]);
^
error: array subscript is not an integer
putchar(userInput[counter]);
^
How can I fix these errors? I'm new to C and can't figure out what it means by the pointer cast error, and why my counter variable isn't working.
My code is as follows:
#include <stdio.h>
#include <string.h>
#include <ctype.h>
int main(void)
{
char *userInput;
int *counter = 0;
printf("Enter a string of characters: ");
userInput = getchar();
while(counter < strlen(userInput))
{
putchar(userInput[counter]);
putchar(userInput[counter]);
putchar(userInput[counter]);
printf("\n");
counter++;
}
}
I'm not really sure why you want to do this, but if I had to do it, I'll probably do it like this -
01 #include <stdio.h>
02 int main()
03 {
04 char userInput[100],c;
05 int length, i=0;
06
07 printf("Enter a string of characters: ");
08 while(c=getchar()){
09 if(c=='\n')
10 break;
11 userInput[i++] = c;
12 }
13 userInput[i]='\0';
14 length = i;
15
16 for(i=0; i<length; i++){
17 putchar(userInput[i]);
18 putchar(userInput[i]);
19 putchar(userInput[i]);
20 putchar('\n');
21 }
22 return 0;
23 }
I've added line numbers for better understanding. Here's what I did -
So this does the task as you wanted to. I tried to make it as beginner friendly as I could, comment for any queries. Glad to help. :)