2

I wrote this code in C++, and I used getchar() to puase the console, but I did not see any effect of using that function, here is the code:

#include<iostream>
#include<stdio.h>//to pause console screen

using namespace std;
//function prototypes
int  getSmallest(int*);
int getOccurrence(int, int*);

int main(){

    int a[7], counter=0, smallest;
    cout<<"Please enter 7 integers"<<endl;
    while(counter!=7){
        cin>>a[counter];
        counter++;
    }
    smallest=getSmallest(a);
    cout<<"The smallest number is "<<smallest<<"; it apears "<<getOccurrence(smallest,a)<<" times"<<endl;
    getchar();//to pause console screen
    return 0;
}

int  getSmallest(int*x){
int count=0, smallest=*x;
//loop till last item in array
while(count!=7){

    if(*x<smallest)
        smallest=*x;
    count++;
    x++;
}
return smallest;
}


int getOccurrence(int smallest, int* address){

int count=0,occ=0;
//loop till last item in array
while(count!=7){

    if(*address==smallest)
    occ++;
    count++;
    address++;
}
return occ;

}
Aan
  • 12,247
  • 36
  • 89
  • 150
  • 4
    Generally it is not good to mix `cin` with the other input functions such as `getchar`. โ€“ Seth Carnegie Dec 09 '11 at 08:03
  • 8
    ยค The *technical* problem is probably that there is at least a newline character left in the input buffer. The *practical solution* to the task of keeping the console window at the end, is to either (1) run the program from the command line, or (2) run it via some utility that stops, such as dragging it onto a batch file with a `pause` command, or using **Ctrl F5** in Visual Studio, or (3) running it in a debugger (e.g. **F5** in Visual Studio) and placing a breakpoint on the closing brace of `main`. There's no need to wait for a key in the program itself. Cheers & hth., โ€“ Cheers and hth. - Alf Dec 09 '11 at 08:10
  • @Sanjay Or maybe that he isn't doing this for reps, but just to help people. (But I agree that it really merits being an answer, if only to be more readily seen. It's the definitive answer to this sort of question.) โ€“ James Kanze Dec 09 '11 at 09:03

5 Answers5

7

As has been pointed out, the issue is that your input buffer had a string for the number AND a newline. C++ I/O skips leading whitespace when it reads something like a number out, but it doesn't take the trailing whitespace out of the buffer. It leaves that for the next read to deal with. So getchar() is getting that newline that's still pending.

Ignore advice from people who are trying to tell you to flush(), ignore(), or clear out "whatever was in the buffer before the getchar() call". These functions have no notions of "non-blocking" input.

Said another way: the usual C++ input stream functions don't have a concept of "there's nothing there right now"...but then you call later and it says "oh, but now there's something!!!" There's an "input sequence" that you can only detect as stopping when you hit EOF.

The exception to this would be readsome()...which rather than operating on an "input sequence" operates on the "input buffer". Finding such a thing, we might try this:

#include<iostream>
#include<cstdio>//to pause console screen

using namespace std;

int main(int argc, char* argv[]) {
    cout << "Enter a number\n";
    int num;
    cin >> num;

    char ch;
    while (cin.readsome(&ch, 1) != 0)
         ;

    cout << "Press any key to continue...\n";
    getchar();
    return 0;
}

But at least on my machine, it doesn't lead to the desired effect. Which means that even though there's a newline sitting in the terminal app or OS pipeline somewhere, it hasn't yet gotten as far as the internal stream buffer object for cin. Upshot is: there is a non-blocking input function based on the buffer, but in this kind of scenario it apparently isn't going to help.

The real answer is what Alf said in the comment. Most decent dev environments or setups will have some way to configure it to not let the console close automatically. If not, hack around it with your launch method. Heck, you can even put a breakpoint on the return 0 in main!


Notes:

You should be aware that "correct" C++ inclusions of compatibility libraries for C are done as #include <cfoo> instead of #include "foo.h". It may not make all that big a difference in practice...but at minimum it distracts from your question when people comment about it (like I'm doing right now):

Is it bad practice to use a C header instead of its C++ equivalent in C++ (e.g. stdio.h instead of cstdio)?

Also, you could have demonstrated this with a much smaller sample! You could have shown the effect simply with:

#include<iostream>
#include<cstdio>//to pause console screen

using namespace std;

int main(int argc, char* argv[]) {
    cout << "Enter a number\n";

    int num;
    cin >> num;

    cout << "Press any key to continue...\n";
    getchar();
    return 0;
}

So try and pare down your examples to really isolate the problem in the future! (Feel free to edit your question to be this succinct in order to make this thread more useful for people searching.)

Community
  • 1
  • 1
1

Try this:

int main()
{
   // ...
   std::cin.get();
   std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');

   return 0;
}
vdsf
  • 1,608
  • 2
  • 18
  • 22
0

thats why they put isspace and ispunct functions in your own function prototypes and have pointers to values b/c cin>> and "while((ch = getchar()) != '\n')" are fpermissive most get away with it is using a pointer and size t which is the return type of the Cstrings function "strlen()"

void remove_whitespace(char *str)
{
    char *p;
    size_t len = strlen(str);

      for(p = str; *p; p ++, len --) {

       while(isspace(*p)) memmove(p, p+1, len--);
}

for the c programming example ... here

char string[100], ch;
int i = 0;
cout<<"Enter a message: ";

while((ch = getchar()) != '\n') //grab users input string untill 
{                               //Enter is pressed
    if (!isspace(ch) && !ispunct(ch)) //Cstring functions checking for
    {                               
        string[i] = tolower(ch); 
        i++;
    }
}

if you want to write only c++ code you have to make your own functions from scratch... or try to use terrible functions that have *'s in them

char name[100];
//string userInput[26];
int i=0, n=0;
cout<<"your name? ";
cin>>name;
cout<<"Hello "<<name<< endl;

char *ptr=name;
for (i = 0; i < 20; i++)
{
cout<<i<<" "<<ptr[i]<<" "<<(int)ptr[i]<<endl;
}   
int length = 0;
while(name[length] != '\0')
{
    length++;
}
cout<<name <<"is"<<length<<"chars long"
0

It may be the problem of the buffer. Because of buffer the getChar takes input from buffer so it will better to flush buffer before calling getChar()

Hemant Metalia
  • 29,730
  • 18
  • 72
  • 91
0

Here are the two alternates:

  1. getch(); you will have to use #include <conio.h>
  2. system("pause");
Taha
  • 1,086
  • 1
  • 10
  • 20