I need to make the program:

Write a program to ask for a string and a single character. Read in the string using getchar(). Read in the character using scanf(). Count and report the number of occurrences of the character in the string. Add a brief comment at the beginning of the file describing what the program does.

An interactive session with the program should look like (note the space at the end of the prompts, that the string appears on a separate line, indented and quoted, and that the character is printed within single quotes; sample user input is in red):

Enter any string: I could have entered anything, but this is what I typed.

Enter any character: t

In the following string:

"I could have entered anything, but this is what I typed."

The character 't' appears 6 times

This is what I got so far, but I'm completely stuck now because I keep getting errors:

#include <stdio.h>
#include <string.h>


int main (int argc, char**argv)
{
	int i;
	int letterCount;
	char LetterToMatch[1];
	char string[220];

	letterCount = 0;
	for(i = 0; i < strlen(string); i++)
	{
		if (string[i] = getchar[LetterToMatch])
			letterCount++;
	
		if (string[i] == '\n')
			{
				break;
			}
	}


	printf("Enter any string: ");
	scanf (" %s", &string);
	printf("Enter any character: ");
	scanf (" %s", &LetterToMatch);
	printf("In the following string:\n");
	printf("  \"%s\"\n", string);
	printf("The character '%c" appears %d time%s\n", 
		LetterToMatch, letterCount, letterCount == 1 ?"":"s");

	return(0);
}

I'm not even positive I have the right syntax, but here are the errors I'm getting for this code:

15:subscripted value is neither array nor pointer
26: warning: char format, different type arg (arg 2)
28: warning: char format, different type arg (arg 2)
31: parse error before "appears"
31: stray '\' in program
31:55: warning: multi-line string literals are deprecated
32:54: warning: multi-line string literals are deprecated
32:54: missing terminating " character
31:55: possible start of unterminated string literal

Please keep in mind that I am a beginner so please try and explain in a way a beginner would understand. Thanks!

getchar uses round parentheses not square brackets to hold the parameters.

you don't need the & address operator on line 26 because arrays are ALWAYS passed by address.

line 28 has a couple problems: if you only want one character then use "%c" instead of "%s". and it has the same problem as above on line 26.

line 31: The double quote immediately after '%c should be a single quote. The rest of the errors will be fixed too when you correct that.

I fixed those things, but I'm still getting errors:

#include <stdio.h>
#include <string.h>


int main (int argc, char**argv)
{
	int i;
	int letterCount;
	char LetterToMatch[1];
	char string[220];

	letterCount = 0;
	for(i = 0; i < strlen(string); i++)
	{
		if (string[i] = getchar(LetterToMatch))
			letterCount++;
	
		if (string[i] == '\n')
			{
				break;
			}
	}


	printf("Enter any string: ");
	scanf (" %c", &string);
	printf("Enter any character: ");
	scanf (" %c", &LetterToMatch);
	printf("In the following string:\n");
	printf("  \"%s\"\n", string);
	printf("The character '%c' appears %d time%s\n", 
		LetterToMatch, letterCount, letterCount == 1 ?"":"s");

	return(0);
}

The errors I'm getting:

15:54: macro "getchar" passed 1 arguments, but takes just 0
In function 'main':
15: warning: assignment makes integer from pointer without cast
15: warning: suggest parentheses around assignment used as truth value
26: warning: char format, different type arg (arg 2)
28: warning: char format, different type arg (arg 2)
32: warning: int format, pointer arg (arg 2)
literal

what have YOU tried to fix the problems? Look at the error messages, they tell you what lines are incorrect. Then look up the function in your textbook or online and see why the compiler says you are wrong.

line 13 is wrong -- what is the value of string when it first enters that loop ? Hint: its value is just some random junk because you didn't initialize it to anything. And even if you did initialize it that line would still be wrong.

Thanks for the help on line 13. I guess I need to look up initializing strings some more and understand it a little better.

I see the errors, I just don't know what they mean. For instance does "char format, different type arg" always mean the letter that comes after "%" (same with int format)? and I don't even know what a truth value or a cast is. and "15:54: macro "getchar" passed 1 arguments, but takes just 0" I don't even understand at all.

And they are not things I can find in my book or online (because I don't even know what to be searching for).

Why is LetterToMatch defined as an array of one char? Why not just define it as a char and it won't be a pointer, correcting some of the errors.

Why is LetterToMatch defined as an array of one char? Why not just define it as a char and it won't be a pointer, correcting some of the errors.

Do you mean making line 9 "char LetterToMatch[];" instead of "char LetterToMatch[1]"?

Because when I do that it says I have an array size missing in "LetterToMatch".

Sorry if this all sounds stupid, I'm having trouble grasping the C language.

Okay, I don't know if it was a very good mistake or if something clicked in my brain but I was able to figure something out, my code is now:

#include <stdio.h>
#include <string.h>


int main (int argc, char**argv)
{
    int i;
    int letterCount;
    char LetterToMatch;
    char string[30];

    letterCount = 0;
    while ( (i = getchar() ) != EOF)
    {
        if (  i >= 'LetterToMatch')
            letterCount++; 
    }


    printf("Enter any string: ");
    scanf (" %c", string);
    printf("Enter any character: ");
    scanf (" %c", &LetterToMatch);
    printf("In the following string:\n");
    printf("  \"%s\"\n", string);
    printf("The character '%c' appears %d time%s\n", 
        LetterToMatch, letterCount, letterCount == 1 ?"":"s");

    return(0);
}

And now the only error I have is

15:28: warning: character constant too long

what does it mean when it says '15:28:'? Is it still referring to lines? And can someone tell me what "character constant too long" means?

Also, the 'while ( (i = getchar() ) != EOF)' I got from the book. does anyone know what EOF is supposed mean?

Also, I tried running the program anyway and when I did a blank line was given where I can type and send, but nothing happens and I can't get out of it.

Thanks

Edited 3 Years Ago by diafol: fixed formatting

>if ( i >= 'LetterToMatch')
I'm going to go out on a limb and guess that you meant:

if ( i == LetterToMatch )

LetterToMatch is a variable, and you're checking to see if i matches it, correct? Also, if you're going to test against LetterToMatch, you need to make sure that it's actually been set to something.

>does anyone know what EOF is supposed mean?
It's supposed to mean end-of-file, or "you've reached the end of the data".

Thank you Narue, you have been extremely helpful! I fixed the if statement and it changed my error to '22:28:' instead of '15:28:' so it must have done something (although i don't know what haha).

>if you'r going to test against LetterToMatch, you need to make sure that it's actually been set to something.
I'm guessing that because you said this that LetterToMatch is not set to anything? I'm so confused, I know how to do this code without the scanf() but not knowing what the letter is is throwing me off.

Should I have a #define LetterToMatch at the beginning?

Another thing I'm having trouble grasping is what exactly (i = getchar() ) is telling the program (again, I'm having troubles understanding getchar, this might be due to the fact I've been up practically all night trying to figure these programs out, :/). Maybe if I understand what (i = getchar() ) is doing I will understand this a little better. (namely I'm confused to what i is even representing...)

Also, do you think I need the '!= EOF' in line 20?

Sorry about all the questions, this is just really frustrating me.

Edit: I also just changed line 22 to "if ( string == 'LetterToMatch')" and I tried running the program anyway and when I did it did ask me to enter any string, but then when I did and sent it it said "Enter any character: In the following screen:" and then went down a new line and is just blank, and I can type anything, but it won't do anything, and it won't let me out of the program.

>I'm guessing that because you said this that LetterToMatch is not set to anything?
Good guess. If you don't set it to anything, then it really could be anything. If you know the character you're going to look for at compile time, then it's trivial. Just do this:

char LetterToMatch = 'A'; /* Assuming you want to find 'A' */

If it's a runtime value that you get from the user, you'd do this instead:

char LetterToMatch;

printf ( "Enter a letter to search for: " );
fflush ( stdout );
LetterToMatch = getchar();

>Another thing I'm having trouble grasping is what exactly (i = getchar() ) is telling the program
getchar is easy. It returns the next character from stdin and returns EOF if it fails to do so for any reason. So if you say this:

int ch;

while ( ( ch = getchar() ) != EOF )
  putchar ( ch );

You're reading characters from stdin (and writing them in that order to stdout) until getchar fails. Assuming you're on a Windows machine, you can signal EOF by typing ctrl+z (that's holding down either ctrl key and then pressing z).

Narue, thank you so much! Your the only person on this site and another site I was asking on that actually answered my questions straight out and in a polite way too. Plus, I was actually able to understand what you were talking about :).

The bit of code you gave me will definitely lead me in the right direction (I don't think we've learned fflush yet, so I don't think we can use it, but we have touched on stdin and stdout so I will try to find another way to use that.)

Anyway, hopefully I can figure this program out (still don't have it quite right, I don't think I'm supposed to be using the where loops, I think I have to use the for loops, so yah...), and then its on to my take home midterm, eek. I just looked at the programs I have to do and I'm a little nervous.

>I don't think we've learned fflush yet, so I don't think we can use it
You probably don't fflush yet, and this explanation may be too much, but store it away for later use:

To be strictly correct and portable, you should flush stdout manually for any user prompt unless you print a '\n' character, because the message might not be visible until the stream is flushed. If you don't print '\n' or call fflush, you have to rely on the buffer being filled up, which could happen at different times depending on your compiler.

This article has been dead for over six months. Start a new discussion instead.