-2

I have 2 questions:

Question 1= i search in the internet and i found that everyone told don't use getch() or getche() in c++. so how can i get a character from user ?? for example i wrote this code so how can i replace getch with another statement ?

Question 2= i wrote this code in visual studio 2013 and it works fine but when i wrote in code block and compile whit GNU GCC compiler getchar() statement doesn't work . why ??

#include <iostream>
#include "conio.h"
using namespace std;

int main()
{
int word_counter=0,char_counter=0;
char ch;
cout<<"Enter your paragraph and press ENTER for end :\n";
cin>>ch;
while((ch=getchar())!=13)
    char_counter++;
cout<<"Number of characters ="<<char_counter<<endl;
return 0;
}
ssaeidd
  • 1
  • 4

3 Answers3

1

First Question: Use cin to get input from the user through the console.

Second Question: getchar() is not supported on GNU gcc compiler as conio is not a part of gcc.`

EDIT:

Use getline() instead of cin as I earlier mentioned since you want the loop to break only when the input is '\n'.

Ayush Gupta
  • 1,589
  • 3
  • 13
  • 23
0

Reponse 1 : getch() is used to ask(read) only one character form the user(or file).

Reponse 2: I suppose that you want to count the number of char.

int main() 
{
char c;
long long  n;
do
{
    cin.get(c);
    cout<<c;
    n++;
}while(c!='.'); 
cout<<n<<endl;

return  0;
}
0

Question 1= i search in the internet and i found that everyone told don't use getch() or getche() in c++. so how can i get a character from user ??

Most environments buffer the text before it gets to your program. You would have to type the text, then press Enter in order to transfer the buffer to your program.

There are no functions nor facilities in standard C++ to get a character from the User as they type it.

You will need to use an OS specific function to fetch a character as the User types it. You may want to also search the internet for the word "keypress".

Question 2= i wrote this code in visual studio 2013 and it works fine but when i wrote in code block and compile whit GNU GCC compiler getchar() statement doesn't work . why ??

As others have stated, the conio.h file is not standard.

According to this reference on getchar, you will need to include stdio for the function.

Also note that the C language streams, such as stdin and printf, may not be compatible with the C++ language streams such as cout and cin. They may have different buffers. Pick one or the other and don't cross the streams.

Thomas Matthews
  • 56,849
  • 17
  • 98
  • 154