CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 15 of 15

Threaded View

  1. #1
    Join Date
    May 2017
    Posts
    10

    Not able to have getche() working in chcount.cpp

    Hi C++ Guru,

    I am having difficulty getting the chcount.cpp program
    to count the number of characters & words entered using getche() library function.
    This program is on page 100 of Object Oriented Programming in C++ by Robert Lafore (4th ED),
    from https://ia801303.us.archive.org/25/items/ObjectOrientedProgrammingInC4thEdition/Object-Oriented%20Programming%20in%20C++%20(4th%20Edition).pdf

    The issue after having debugged it was that ch has been assigned a random characters / numbers
    (e.g. 1, 0..), before I get to enter any character, which resulted in stucked in WHILE loop.

    Below is the code snippet:
    Code:
    // chcount.cpp
    #include <iostream>
    #include <conio.h>				// for getche()
    
    using namespace std;
    
    int main()
    {
    	int chcount = 0;				// counts non-space characters
    	int wdcount = 1;				// counts spaces between words
    	char ch = 'a';					// ensure it isn't '\r'
    
    	while( ch != '\r' ) 	//loop until Enter is typed
    	{
    //		ch = getchar(); 			// Read a character before I enter anything
    		ch = getche(); 				// Not running getche() function.
    		if ( ch == ' ' )			// if it's a space
    			wdcount++;				// count it as a word
    		else						// otherwise,
    			chcount++;				// count a character
    	}
    	cout << "\nWords=" << wdcount << endl
    	     << "Letters=" << chcount-1 << endl;
    	return 0;
    }
    getche() did not process further while getchar() simply accept random characters / numbers (e.g. 1,0)
    before I get to enter anything in.

    I have tried other functions such as getc(stdin) & getch() & lookup similar resolutions
    without success for a few hours.

    I am running Eclipse C/C++ Neon.3 (4.6.3 - 20170314-1500)
    with MinGW-w64 on Windows 10.

    Your assistance would be much appreciated.

    Thanks,

    George
    Attached Files Attached Files

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured