Solved

How do I count spaces and newlines?

Posted on 2009-04-05
12
646 Views
Last Modified: 2012-05-06
I want to create a program that reads a sentence that you type and tells you how many spaces, newlines, and letters are in that sentence
nt main () {
    int count;
	int spaces = 0;
	int newline = 0;
	printf("Type a sentence: ");
	while ((count = getchar()) != '\0')
	{
		if(count == ' ')
			spaces ++;
		if(count == '\n')
			newline ++;
		putchar(count);
    }
	printf("I counted %d spaces, %d newline characters, and %d total characters.\n", spaces , newline, (count - spaces - newline));
 
	return 0;
}

Open in new window

0
Comment
Question by:prebek
  • 6
  • 3
  • 2
  • +1
12 Comments
 
LVL 53

Expert Comment

by:Infinity08
ID: 24072516
Except that getchar won't return '\0' to signify the end of the input, that looks ok.

Why not use fgets to read an entire line of input into a C string, and then loop over every character of that string ?

        http://cplusplus.com/reference/clibrary/cstdio/fgets.html
0
 
LVL 7

Expert Comment

by:cmrobertson
ID: 24072559
or a regular expression to count them
0
 
LVL 53

Expert Comment

by:Infinity08
ID: 24072574
Oh, and in case that wasn't clear ... My approach makes it easy to count newlines, as each line read with fgets has exactly one newline character (per definition) - so you don't really need to check for newline characters ;) You simply count the number of fgets's :)
0
Microsoft Certification Exam 74-409

Veeam® is happy to provide the Microsoft community with a study guide prepared by MVP and MCT, Orin Thomas. This guide will take you through each of the exam objectives, helping you to prepare for and pass the examination.

 
LVL 40

Expert Comment

by:mrjoltcola
ID: 24072585
As Infinity said, you need to use (while(count = getchar()) != EOF), don't use '\0'

Also, you are using 'count' in the end for some arithmetic, but it has no sum/number in it, its used in your program just to read a character. So you need to use 2 different variables, and at least increment count every loop.



0
 
LVL 40

Expert Comment

by:mrjoltcola
ID: 24072592
@cmrobertson: How would you count characters with a regex in a simple C program?
0
 

Author Comment

by:prebek
ID: 24072608
Infinity, I used your fgets approach and I implemented arrays as well. Now it reads spaces and newlines well, but it gives a a strange number format for the number of letters. Why is that?

int main ()
      {
            int CHARACTERS;
    char count[CHARACTERS];
      int i;
      int spaces = 0;
      int newline = 0;
      printf("Type a sentence: ");
            CHARACTERS = fgets(count, 20, stdin);
      while (count[i] != '\0')
      {
            if(count[i] == ' ')
                  spaces ++;
            if(count[i] == '\n')
                  newline ++;
            i++;
//            putchar(count);
    }
      printf("I counted %d spaces, %d newline characters, and %d letters.\n", spaces , newline, (CHARACTERS-spaces-newline));

      return 0;
}
0
 
LVL 53

Accepted Solution

by:
Infinity08 earned 500 total points
ID: 24072628
>>             int CHARACTERS;
>>     char count[CHARACTERS];

You need to specify a certain size here for the array, like 1024 for example. Pick a size that will cover the longest line of text.

You probably also want to choose a more fitting variable name, like 'line' for example, rather than 'count'.


>>       int i;

You need to initialize this variable (to 0).


>>             CHARACTERS = fgets(count, 20, stdin);

fgets does not return an integer value. It returns a pointer to the string it just read (or NULL if reading failed for some reason). See the reference page I posted earlier for more detail.

You'll also want to call fgets in a loop, to get all lines of input, and you'll want to match the second argument to the size of the C string (1024 for example).


>>             if(count[i] == '\n')
>>                   newline ++;

You don't really need to check for this, since you know there will be one newline character for each line you read with fgets.
0
 
LVL 53

Expert Comment

by:Infinity08
ID: 24072630
Oh, and to get the number of characters on a line, you can make use of strlen.
0
 

Author Comment

by:prebek
ID: 24072634
Ok, I initialized i and CHARACTERS like you suggested, and it seems to work now. Let me know if you see anything wrong:

int main ()
      {
            int CHARACTERS = 50;
    char count[CHARACTERS];
      int i = 0;
      int spaces = 0;
      int newline = 0;
      printf("Type a sentence: ");
            CHARACTERS = printf("%s", fgets(count, 20, stdin));
      while (count[i] != '\0')
      {
            if(count[i] == ' ')
                  spaces ++;
            if(count[i] == '\n')
                  newline ++;
            i++;
//            putchar(count);
    }
      printf("I counted %d spaces, %d newline characters, and %d total characters.\n", spaces , newline, (CHARACTERS-spaces-newline));

      return 0;
}
0
 
LVL 53

Expert Comment

by:Infinity08
ID: 24072643
The other things I pointed out ;)


>> You probably also want to choose a more fitting variable name, like 'line' for example, rather than 'count'.

>> >>             CHARACTERS = fgets(count, 20, stdin);
>> 
>> fgets does not return an integer value. It returns a pointer to the string it just read (or NULL if reading failed for
>> some reason). See the reference page I posted earlier for more detail.
>> 
>> You'll also want to call fgets in a loop, to get all lines of input, and you'll want to match the second argument to the
>> size of the C string (1024 for example).

>> >>             if(count[i] == '\n')
>> >>                   newline ++;
>> 
>> You don't really need to check for this, since you know there will be one newline character for each line you read
>> with fgets.
0
 

Author Closing Comment

by:prebek
ID: 31566803
good fgets() suggestion, and the suggestion about pointers not equaling integer values was helpful too. thanks
0
 
LVL 53

Expert Comment

by:Infinity08
ID: 24072646
May I ask why you gave a B grade ? That usually means that something was missing in the answer and/or that something was still unclear. If so, then please do not hesitate to ask for clarification.
0

Featured Post

Ransomware-A Revenue Bonanza for Service Providers

Ransomware – malware that gets on your customers’ computers, encrypts their data, and extorts a hefty ransom for the decryption keys – is a surging new threat.  The purpose of this eBook is to educate the reader about ransomware attacks.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
Picking random number 8 177
undefined reference to `bswap_128' 9 160
mixing C++ and C code elegantly 10 156
c++ substatte a varabe for a string in a LPCTSTR statment 8 85
Preface I don't like visual development tools that are supposed to write a program for me. Even if it is Xcode and I can use Interface Builder. Yes, it is a perfect tool and has helped me a lot, mainly, in the beginning, when my programs were small…
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 recursion in the C programming language.
The goal of this video is to provide viewers with basic examples to understand how to use strings and some functions related to them in the C programming language.

776 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