C++: getchar() vs. _getch() - c++

I've read that getchar() should actually be preferred over _getch() ( _getch() also needs including conio.h ). However, if I use getchar() in this sample program...
#include <iostream>
#include <conio.h>
using namespace std;
class student {
int id;
int marks;
public:
void getdata() {
cout << "\n Enter id";
cin >> id;
cout << "\n Enter marks";
cin >> marks;
}
void putdata() {
cout << "\n" << id << "\t" << marks;
}
};
int main() {
student tom;
tom.getdata();
tom.putdata();
getchar(); // vs. _getch();
return 0;
}
..then using getchar() won't wait for the input of a character to prevent the console window from being closed too early, which _getch() does.
Does anyone know the reason for this? And should getchar() really be preferred over _getch()?
BTW, I'm using MS Visual Studio 2015.
Thanks in advance and kind regards
EDIT: I'd consider my question as not being a duplicate actually, since I was wondering about the reason for the different behavior, which had not been answered under "Is there a decent wait function in C++?", and which got clarified now.

Related

Why i cant get input? [duplicate]

#include <string>
std::string input;
std::cin >> input;
The user wants to enter "Hello World". But cin fails at the space between the two words. How can I make cin take in the whole of Hello World?
I'm actually doing this with structs and cin.getline doesn't seem to work. Here's my code:
struct cd
{
std::string CDTitle[50];
std::string Artist[50];
int number_of_songs[50];
};
std::cin.getline(library.number_of_songs[libNumber], 250);
This yields an error. Any ideas?
It doesn't "fail"; it just stops reading. It sees a lexical token as a "string".
Use std::getline:
#include <string>
#include <iostream>
int main()
{
std::string name, title;
std::cout << "Enter your name: ";
std::getline(std::cin, name);
std::cout << "Enter your favourite movie: ";
std::getline(std::cin, title);
std::cout << name << "'s favourite movie is " << title;
}
Note that this is not the same as std::istream::getline, which works with C-style char buffers rather than std::strings.
Update
Your edited question bears little resemblance to the original.
You were trying to getline into an int, not a string or character buffer. The formatting operations of streams only work with operator<< and operator>>. Either use one of them (and tweak accordingly for multi-word input), or use getline and lexically convert to int after-the-fact.
You have to use cin.getline():
char input[100];
cin.getline(input,sizeof(input));
The Standard Library provides an input function called ws, which consumes whitespace from an input stream. You can use it like this:
std::string s;
std::getline(std::cin >> std::ws, s);
Use :
getline(cin, input);
the function can be found in
#include <string>
You want to use the .getline function in cin.
#include <iostream>
using namespace std;
int main () {
char name[256], title[256];
cout << "Enter your name: ";
cin.getline (name,256);
cout << "Enter your favourite movie: ";
cin.getline (title,256);
cout << name << "'s favourite movie is " << title;
return 0;
}
Took the example from here. Check it out for more info and examples.
How do I read a string from input?
You can read a single, whitespace terminated word with std::cin like this:
#include<iostream>
#include<string>
using namespace std;
int main()
{
cout << "Please enter a word:\n";
string s;
cin>>s;
cout << "You entered " << s << '\n';
}
Note that there is no explicit memory management and no fixed-sized buffer that you could possibly overflow.
If you really need a whole line (and not just a single word) you can do this:
#include<iostream>
#include<string>
using namespace std;
int main()
{
cout << "Please enter a line:\n";
string s;
getline(cin,s);
cout << "You entered " << s << '\n';
}
THE C WAY
You can use gets function found in cstdio(stdio.h in c):
#include<cstdio>
int main(){
char name[256];
gets(name); // for input
puts(name);// for printing
}
THE C++ WAY
gets is removed in c++11.
[Recommended]:You can use getline(cin,name) which is in string.h
or cin.getline(name,256) which is in iostream itself.
#include<iostream>
#include<string>
using namespace std;
int main(){
char name1[256];
string name2;
cin.getline(name1,256); // for input
getline(cin,name2); // for input
cout<<name1<<"\n"<<name2;// for printing
}
I rather use the following method to get the input:
#include <iostream>
#include <string>
using namespace std;
int main(void) {
string name;
cout << "Hello, Input your name please: ";
getline(cin, name);
return 0;
}
It's actually super easy to use rather than defining the total length of array for a string which contains a space character.

Why the program is not working properly?

I new to programming and was trying to implement struct program in c++, it's simple program but it's not printing proper result. please tell me why?
#include <iostream>
using namespace std;
struct classroom {
int number;
char name[9];
int marks;
void getAndPrint()
{
cout << "struct classroom ";
cin >> number;
cout << number << '\n';
cin.get(name, 9);
//cin>>name;
cout << name;
cin >> marks;
cout << marks;
}
};
int main()
{
classroom room1;
room1.getAndPrint();
int i;
cin >> i;
return 0;
}
In function getAndPrint() I'm using cin.get()..the compiler execute the properly till printing the "number" but when it comes on cin.get(name,9) it print garbage and skips the rest of the code inside the funcion. If i use cin>>name then it's working properly.
Can anyone tell what exactly is the problem?
first, in C++, struct is class with access_modifier is public.
second, you should try read:
Difference between cin and cin.get() for char array
The structure definition does not contain such a function like see
room1.see();
^^^^
I think you mean
room1.getAndPrint();
Also before this statement
cin.get(name, 9);
insert at least this statement
cin.ignore();
Or you even can include the header <limits> and insert statement
#include <limits>
//...
cin.ignore( std::numeric_limits<streamsize>::max(), '\n' );

How do I create rows in an output file? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I currently have this code and all of the formatting is correct... I just can't seem to get it to create rows in the output text file... How would I do this? I've tried to do a for loop in the function and in the main() but it seems to not work if I do that so I am very confused right now.
#include <iostream>
#include <string>
#include <fstream>
#include <iomanip>
using namespace std;
void output(string flightnumber, int arrival1, int arrival2, int realarrival1, int realarrival2, char dummy1, char dummy2)
{
ofstream flight;
flight.open("flightdata.dat");
if (flight.fail())
{
cout << "Error..." << endl;
exit(1);
}
cout << "Enter the flight number: ";
cin >> flightnumber;
if (flightnumber == "end")
{
exit(1);
}
flight << flightnumber << setw(4);
cout << "Enter the scheduled/actual arrival times (hh:mm hh:mm):";
cin >> arrival1 >> dummy1 >> arrival2 >> realarrival1 >> dummy2 >> realarrival2;
flight << arrival1 << dummy1 << arrival2 << setw(4) << realarrival1 << dummy2 << realarrival2;
flight << ('\n');
}
int main()
{
string flightnumber;
int arrival1, arrival2, realarrival1, realarrival2;
char dummy1, dummy2;
output(flightnumber, arrival1, arrival2, realarrival1, realarrival2, dummy1, dummy2);
return 0;
}
You are not appending your file whenever you write it truncates and creates a new file, add appending flag and open your file as.
flight.open("flightdata.dat", ios_base::app);
You are using uninitialized variables in main. They serve no purpose in there anyway. Remove variable declarations from main and put them in output:
void output()
{
string flightnumber;
int arrival1, arrival2, realarrival1, realarrival2;
char dummy1, dummy2;
ofstream flight;
flight.open("c:\\test\\___flightdata.txt", ios::app);
...
}
int main()
{
output();
return 0;
}
You may want to add ios::app flag as pointed out in the other answer.

Console UI with User input

So i'm trying to make a simple console application that asks the user for certain characteristics. The first question, asks the user for their age. For example, it should look like "I am >enter age< years old" I've been having a lot of console application problems, so I'll probably be moving to GUI interfaces in the future.. Until then, I think this is good practice. Heres my code. (Sorry for not using the code format, it doesnt seem to work properly on my mobile)
#include <iostream>
#include <string>
using namespace std;
//Variables
int Age;
//Functions
int AgeEnt(){
cin >> Age;
return Age;
}
//Main
int main (){
cout << "Welcome! Please enter your age to continue\n";
cout << "I am " << AgeEnt << " years old";
return 0;
}
This automatically puts a 1 where the age should be. How would I make it to where I can input a number between the text? Im still a beginner so excuse me if this isnt possible in console, or extremely depreciated.
int main (){
cout << "Welcome! Please enter your age to continue\n";
int age;
cin >> age;
return 0;
}
Also, why do you declare functions and variables above your main? Except for global functions, this is not needed in C++
#include <iostream>
using namespace std;
//Functions
int AgeEnt(){
int Age;
cin >> Age;
return Age;
}
//Main
int main (){
cout << "Welcome! Please enter your age to continue\n";
AgeEnt();
cout << "I am " << AgeEnt() << " years old";
return 0;
}
A few things
You don't need the <string> header file for this. Its not being used anywhere.
You don't need to declare Age as a global variable. Its only being used in one function so declare it in that.
Also, although i haven't done it here, i would usually do something like int a = AgeEnt(); cout<<a;

c++- variables to system()

I am working on a console program for Windows, and one of my settings is an option to change the console and text color.
I am using c++, so I can do something like system("color 07");, which will make the background black and the text white.
What I want to do is to present all 16 color options, and then let the user take his pick.
(Below is a portion of my code):
int a;
int b;
cout << "Please enter your background color." << endl;
cin >> a; //the user inputs 0
cout << "Please enter your text color." << endl;
cin >> b; //the user inputs 7
How to I pass the two variables to the system() call? I googled around, but all I could find were string to system(), which I do not want.
Also, I am very well aware of how evil system() is, so if anyone has other options other than system() that will do the same thing, that would be fine. But please do not tell me how evil system() is.
Thanks in advance!!
The system command takes a single const char* parameter. Therefore you just need to build a string for the command you wish to execute.
#include <iostream>
#include <sstream>
#include <string>
int main()
{
int backgroundColor;
std::cout << "Enter background color\n";
std::cin >> backgroundColor;
int foregroundColor;
std::cout << "Enter foreground color\n";
std::cin >> foregroundColor;
std::stringstream stream;
stream << "color " << backgroundColor << foregroundColor;
std::cout << "Command to execute: '" << stream.str() << "'\n";
::system(stream.str().c_str());
return 0;
}
This could be a simpler solution using C++ constructs.
#include <iostream>
#include <string>
#include <cstdlib>
using namespace std;
int main()
{
string bgClr,fgClr;
cin >> bgClr >> fgClr;
::system((bgClr+fgClr).c_str());
return EXIT_SUCCESS;
}
char command[500] = "";
sprintf(command, "color(%d, %d)", a, b);
int result = system(command);