2 Replies - 430 Views - Last Post: 23 October 2009 - 12:24 PM Rate Topic: -----

#1 rin_lin  Icon User is offline

  • New D.I.C Head

Reputation: 1
  • View blog
  • Posts: 19
  • Joined: 16-October 09

i'm having problem with the output

Post icon  Posted 23 October 2009 - 12:01 PM

The question of this assessment is write a program to read a sentence which is also consist of numbers. Identify how many words in that sentence and list the numbers.

Here is my coding:
#include <stdio.h>
#include <conio.h>

main() {
   char str[200];
   int space = 0;

   printf("This program is to identify how many words in a sentence and list the numbers.");
   printf("Enter the string: ");
   gets(str);

   for (int i=0; i<200; i++) {
   	if(str[i] == ' ')
		  space++;

	  if((str[i] >= '0') && (str[i] <= '9'))
		  printf("\nThe number in this sentence is %c", str[i]);
   }
   printf("\n\n");
   printf("Number of words: %d", space);

   getch();
   return 0;
}



Even if I didn't enter any character, the output will appeared as follows:
This program is to identify how many words in a sentence and list the numbers.

Enter the string: 

The number in this string is 2  
The number in this string is 8

The number of words: 1 



Is This A Good Question/Topic? 0
  • +

Replies To: i'm having problem with the output

#2 brds  Icon User is offline

  • D.I.C Addict
  • member icon

Reputation: 76
  • View blog
  • Posts: 515
  • Joined: 22-October 08

Re: i'm having problem with the output

Posted 23 October 2009 - 12:16 PM

Checking all 200 characters is whats doing it to you. Just assigning memory doesn't change the values that are already present @ its location. Why don't you limit i to a number lower than strlen(str) so that it only checks what is necessary?
Was This Post Helpful? 0
  • +
  • -

#3 jwwicks  Icon User is offline

  • D.I.C Head
  • member icon

Reputation: 24
  • View blog
  • Posts: 162
  • Joined: 31-July 08

Re: i'm having problem with the output

Posted 23 October 2009 - 12:24 PM

Hello,

View Postrin_lin, on 23 Oct, 2009 - 11:01 AM, said:

The question of this assessment is write a program to read a sentence which is also consist of numbers. Identify how many words in that sentence and list the numbers.

This program is to identify how many words in a sentence and list the numbers.

Enter the string:

The number in this string is 2
The number in this string is 8

The number of words: 1


First thing is initialize
 str[0]= '\0';



Next you need to guard against null in the for loop and use isspace so tabs spaces etc.. get counted
for (int i=0; i<200 && str[i]; i++) {
 if(isspace(str[i]))
   space++;



isspace is in ctype.h

Jw
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1