i get confused whit get character from user - c++

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;
}

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'.

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;
}

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.

Related

CLion is automatically printing back input from standard input, is there any fix for this?

I am trying out CLion to write some basic C++ programs but every time I feed in some input using std::cin or std::getline the input is printed back to the console for no reason.
For example if I run this program
#include <iostream>
#include <string>
int main(){
string name;
std::cin >> name;
std::cout << name << std::endl;
return 0;
}
and type thomas and press enter I get this output
thomas
thomas
thomas
when instead I should get just
thomas
thomas
I am using CLion/Mingw64 on Windows 10 x64
There's nothing wrong with your code.
What you observe is a side effect of using WinPTY under the hood. By default, CLion uses it to communicate with a debugged program on Windows.
Here's the corresponding bug in our issue tracker: CPP-2580 User input appears twice in output window in CLion under MinGW, please feel free to upvote the ticket.
While there's no proper fix for the issue yet, you may use a workaround suggested in comments to that ticket to disable PTY:
Open Registry via Find Action, type run.processes.with.pty and disable this pty setting.

C++: Flawed console output on using a conditional statement

I'm a newbie to C++ (and to programming in general). I wrote a program that reads and writes staff contact details. This code works well:
// appropriate headers...
int main()
{
char trigger{};
int options = 0;
bool testing{};
fileIps Inptbox; // for entering new data
char ext_title[20]; char ext_intercomNum[4]; char ext_dept[20];
printf("%s", "Enter Officer's Title:\n");
gets_s(ext_title, 20);
printf("%s", "Enter Officer's Intercom Number:\n");
gets_s(ext_intercomNum, 4);
printf("%s", "Enter Officer's Department:\n");
gets_s(ext_dept, 20);
Inptbox.rcv_values(ext_title, ext_intercomNum, ext_dept);
Inptbox.create_string();
testing = Inptbox.validate();
if (testing == true)
return -1;
else if (testing == false)
Inptbox.write_string();
// more code below...
My question is regarding the console output. I had tried to introduce conditional statements to enable selecting a read or write mode. The above code is for writing to file. There are more lines of code below for reading from file and they, too, worked okay.
My challenge is that once I introduce a conditional statement for the above code...
printf("%s", "Enter 1 to WRITE DATA or 2 to READ DATA\n");
cin >> options;
if (options == 1)
{
fileIps Inptbox; // for entering new data
//... rest of code...
}
// more code below...
...the output on the console is flawed, as the prompt for the first entry is displayed but is totally skipped, forcing the user to enter 'Officer's Intercom Number' first. The third prompt worked well.
To elaborate further, when I used cin to assign the value 1 to options (i.e. applying the condition), the console would immediately print...
Enter Officer's Title:
Enter Officer's Intercom Number:
...making it impossible for me to fill in the first entry (i.e. 'Title').
I struggled with this and tried several things to fix it. I used fgets() and even tried it with gets(). I revisited my classes, yet nothing worked. I read widely on things like buffering, studied questions on this site and looked through various resources on cstdio as well as ios_base and its derived classes (which was good because I learned a bunch of other things). However, unless I removed that 'if' statement from my code, nothing I else I tried worked.
So, my question is: "How can this kind of behaviour be explained and how best could I implement my code to enable me toggle between read and write mode?"
I am working with MS Visual Studio 2015.
Using the formatted extraction operator '>>' has its problems. In this case, it reads all values that can convert to an integer. However, you must give an enter to signal that you're ready. The >> operator does not process that newline. When the next time input is read, it sees the previously given newline character. Hence the 'Enter Officer's title' input is immediately set to a newline and continues. Try using something like:
std::string line;
getline(cin, line);
And test the string or convert it.

Why does getchar work like a buffer instead of working as expected in real-time

This is my first question on stackoverflow. Pardon me if I haven't searched properly but I do not seem to find an explanation for this. Was just attempting an example from Bjourne Stroustroup's papers. Added my bits to see the array get re-sized as I type the text.
But it doesn't seem to work that way! getchar() simply waits till I am done with entering all the characters and then it will execute the loop. As per the logic, it doesn't actually go into the loop, get a character, perform its actions and then iterate. I am wondering if this is implementation specific, or intended to be like this?
I am on Ubuntu 14.04 LTS using Codeblocks with gcc 4.8.2. The source was in cpp files if that matters.
while(true)
{
int c = getchar();
if(c=='\n' || c==EOF)
{
text[i] = 0;
break;
}
text[i] = c;
if(i == maxsize-1)
{
maxsize = maxsize+maxsize;
text = (char*)realloc(text,maxsize);
if(text == 0) exit(1);
cout << "\n Increasing array size to " << maxsize << endl;
}
i++;
}
The output is as follows:
Array Size is now: 10
Please enter some text: this is some sample text. I would have liked to see the memory being realloced right here, but apparently that's not how it works!
Increasing array size to 20
Increasing array size to 40
Increasing array size to 80
Increasing array size to 160
You have entered: this is some sample text. I would have liked to see the memory being realloced right here, but apparently that's not how it works!
Array Size is now: 160
This has nothing to do with getchar directly. The "problem" is the underlying terminal, which will buffer your Input. The Input is sent to the program after you press enter. In Linux (dunno if there is a way in Windows) you can workaround this by calling
/bin/stty raw
in terminal or by calling
system ("/bin/stty raw");
in your program. This will cause getchar to immediately return the input character to you.
Dont forget to reset the tty behaviour by calling
/bin/stty cooked
when done!
Here is an example (for Linux):
#include <stdio.h>
#include <stdlib.h>
using namespace std;
int main() {
system ("/bin/stty raw");
char c = getchar();
system ("/bin/stty cooked");
return 0;
}
Also have a look at this SO Post: How to avoid press enter with any getchar()
Also, as suggested in the comments, have a look here: http://linux.die.net/man/3/termios especially on the command tcsetattr, which should work cross-platform.
Actually, tcsetattr does not apply to Windows (which is what is commonly referred to in this site as "cross-platform"). However, the question is tagged for Linux, so "cross-platform" is a moot point.
By default the standard input, output and error streams are set to
line-buffered (input)
block-buffered (output)
line-buffered (error)
You can change that using setbuf, but of course will not solve the problem (the answer calls for single-character input). POSIX terminal I/O (termios) lets you change via a system call any of the flags shown using stty. As a rule, you might call stty directly from a script, rarely from a C program.
Reading a single character is a frequently asked question, e.g.,
How can I read single characters from the terminal? (unix-faq)
How can I read a single character from the keyboard without waiting for the RETURN key? How can I stop characters from being echoed on the screen as they're typed? (comp.lang.c FAQ)
You could also use ncurses: the filter function is useful for programs that process a command-line (rather than a full-screen application). There is a sample program in ncurses-examples (filter.c) which does this.

in c++, is it possible to / how can i display console output after input, on same line, before user's input is given?

In C++, when writing to and taking information from the console using cout / cin, is it possible to do something like
ENTER YOUR DATA HERE --> __ <-- ENTER YOUR DATA HERE
With the user input cursor where the underscores are located, and output located on either side of the cursor, and then the user's typed input appearing between those two bits of output before being returned to cin?
If so how would I got about doing that?
I hope that between my title and explanation here that it's clear what I'm asking, if not I can try to explain further.
Ideally I'd like to do this using iostream / cin & cout, because those are what I've used in the past. If the solution is to use... printf or similar I'll do that but may need a bit of additional explanation since I'm not really experienced in using that for output.
NOTE: I tried to find an answer for this problem and I can't say for sure that there wasn't one, it was mostly just a matter of finding a huge amount of other input/output-related questions.
EDIT: This is using the DOS shell on Windows 7, compiling from the Windows Visual Studio 2012 command-line compiler.
If Windows, use the Console API. http://msdn.microsoft.com/en-us/library/windows/desktop/ms682073(v=vs.85).aspx
If Linux, use the curses library: http://en.wikipedia.org/wiki/Ncurses
If you are using windows you have the option to use the conio.h.
#include<iostream.h>
#include<conio.h>
int main()
{
clrscr();
gotoxy(5,3);
cout<<"HELLO WORLD";
gotoxy(60,10);
cout<<"HELLO WORLD";
gotoxy(35,20);
cout<<"HELLO WORLD";
getch();
return 0;
}
If you wish to use ANSI libraries only, you can try to take a look at this discussion:
http://www.cplusplus.com/forum/lounge/78225/
In both cases all you have to do is print the first text, then use gotoxy, then you print seconde text, gotoxy again where you want the input to happens, and read the user input.

Getline() Not keeping Application Open?

I'm a first semester C++ student and in class we are building a BMI calculator (Win32 Console Application). I've gotten everything to work just fine, except for one of the instructions, which is wait for user to press enter to close application.
I had success using the system("PAUSE"); statement but in the past I would declare a string variable, like for example, initialize string genVar; and then use getline(cin, genVar); and when the user pressed Enter, the application would close, but it didnt work this time. The application would simply close. It worked just fine with pause, but not with getline().
Is using getline() for this purpose bad practice? Anyone have any clue why it didn't work?
Thank you in advance!
I know this is an old post, but look at the solution which I posted in this question:
C++ Multiple Program Issues (rand, conversion, crashing)
It explains (as chris mentioned in a comment) that getline tends to leave in a new line character in the buffer, which needs to be cleared and reset. Answer above explains it.
std::cin and std::getline do not mix well in general, you usually want to stick to one or the other in a program to avoid input errors and bugs. Your getline probably is grabbing a left over input from as earlier std::cin. I would recommend using this:
std::cout << "Press ENTER to continue...";
std::cin.ignore( std::numeric_limits<std::streamsize>::max(), '\n' );
return 0;
}
you'll need to include <limits> for this to work correctly.
you can also use the getch() function in the place of std::getline() IMHO