Simple Input validation - cin.ignore (error) - c++

I have this problem while watching tutorials and make one for myself.
I can't get a hold of this cin.ignore(). I want the user to type characters only but if he types any integer, it should continue looping until he gets the correct input.
This is my code along with the error mentioned.
#include <iostream>
#include <vector>
#include <climits>
using namespace std;
// simple io validation
int main(){
char name{};
char last{};
int birthday {};
cout << "Pls Enter your first name: ";
cin>>name; // if he type "alfred123 Philip" it should error
while (!cin.good()) // or while cin.fail()
{
cout<<"Please enter character only"<<endl;
cin.clear();
cin.ignore(INT_MAX,"/n"); //error no instance of overloaded function "std::basic_istream<_CharT, _Traits>::ignore [with _CharT=char, _Traits=std::char_traits<char>]" matches the argument list
cout<<"Enter Name: "; // ask again the user
cin >> name;
}
cout << endl;
cout<<"Hello "<<name<<endl;
return 0;
}

Related

My c++ program terminated without taking the input.What should i do?

The code below,works fine but it does not take any value for age and terminates.`
#include <iostream>
#include <string>
using namespace std;
class user{
int id,level=1,kills=0,age;
char name[20],server[40];
public:
void get(){
cout<<"Enter your name:";
cin>>name[20];
cout<<"Enter your age:";
cin>>age;
}
};
int main(){
user u;
u.get();
return 0;
}
/*Output
Enter your name:Jack
Enter your age:
C:\Users\user\documents\c++
*/
In the output section ,age is not accepted and the program terminates.
Use string name instead of char name[20] to take multi-character value. char name[20] will terminate after taking a single character.
Also, its valued will not be displayed on giving output.
Modified code for reference.
#include <iostream>
#include <string>
using namespace std;
class user{
int id,level=1,kills=0,age;
string name,server;
public:
void get(){
cout<<"Enter your name:";
cin>>name;
cout<<"Enter your age:";
cin>>age;
}
//test output
void put(){
cout<<name<<endl;
cout<<age<<endl;
}
};
int main(){
user u;
u.get();
//test
u.put();
return 0;
}
Just modify the code to this :
#include <iostream>
#include <string>
using namespace std;
class user{
int id,level=1,kills=0,age;
char name[20],server[40];
public:
void get(){
cout<<"Enter your name:";
cin>>name; // changes done here
cout<<"Enter your age:";
cin>>age;
}
};
int main(){
user u;
u.get();
return 0;
}
Job Done :)
Your problem is here:
cin>>name[20];
Why:
'name[20]' is 21th char of the array you defined before. It counts from 0! As this, it is simply a single char. If you now enter more than a single char, the rest is read by the cin>>age.
Example:
cout<<"Enter your name:";
cin>>name[20];
cout<<"Enter your age:";
cin>>age;
std::cout << "Name " << name << std::endl;
std::cout << "Age " << age << std::endl;
And entering:
Enter your name:1234
Enter your age:Name
Age 234
As you see, the '1' is now in the name and the rest is stored in age.
But attention: You defined your array as `name[20], which means you have 0..19 elements. Accessing name[20] is wrong!
But what you simply want to do was:
cin >> name;
The easiest way to handle strings (a long sequence of characters) or even the strings that have spaces just use the following library in C++.
#include <bits/stdc++.h>
Then just declare a string variable.
String name;
Now you can save a very long string without any error. e.g.
name = jshkad skshdur kslsjue djsdf2341;
and you'll get no error, enjoy ;)

Why is cin operation undefined?

#include <iostream>
#include <fstream>
#include <string>
using namespace std;
main()
{
bool string1[20];
cout << "Enter string: ";
cin >> string1;
int counter = 0;
int length;
length = strlen(string1);
This is incomplete code, but my question is why am I getting a compiling error when using cin? It says:
error: no match for ‘operator>>’ (operand types are ‘std::istream {aka std::basic_istream<char>}’ and ‘bool [20]’)
On this line:
cin >> string1;
I'm not sure how to fix this.
bool string1[20]; is the wrong choice for the user input as a string, all it does is create an array of 20booleans, true or false which is not what you want.
what you are after is your included #include <string>
string string1;
cout << "Enter string: ";
cin >> string1;
Instead of using strlen you get the length by using the length method provided by std::string
auto length = string1.length()
There is no operator>> for reading an array of bool values. What you need is an array of char values instead:
#include <iostream>
#include <string>
#include <iomanip>
using namespace std;
int main() {
char string1[20];
cout << "Enter string: ";
cin >> setw(20) >> string1;
int length = strlen(string1);
Or better, a single std::string:
#include <iostream>
#include <string>
using namespace std;
int main() {
string string1;
cout << "Enter string: ";
cin >> string1;
int length = string1.length();
I think you are confusing string with array. string1 in your code is not an string its an array. So, you can't just put data in it without giving the proper index number. Also remember its an bool type so you can only enter 0/1/true/false value.
Again, you have used strlen() function in your code which is used for determining the length of the string but your is an array. You didn't ask about this but when I ran the code in my IDE it got error.
Here is one way to do it :
main()
{
bool string1[20];
cout << "Enter string: ";
for(int i=0;i<20;i++)//iterating through the boolian array
{
cin >> string1[i];
}
int counter = 0;
int length;
length = sizeof(string1)/sizeof(string1[0]);
cout<<length;//printing the size of the array
}

C++ getline won't work with int?

I've been working on this project for my C++ class in which I have to get a collection of information from the user, including the users birthyear and the current year (we have yet to learn how to access the computer's date so it has to be manually retrieved). I'm still fairly early in the process and I've run into this obstacle that I can't seem to work around.
While I've used this process to easily get the name system to work using the custom class, I can't get it to work for the year value. I can only assume the issue is that the year is an int rather than a string, but I can't possibly figure out any other way to get this to work. Could someone please look at this code and help me figure out what the issue is?
Main class:
#include <iostream>
#include <string>
#include "Heartrates.h"
using namespace std;
int main() {
Heartrates myHeartrate;
cout << "Please enter your name (First and Last): ";
string yourName;
getline (cin, yourName);
myHeartrate.setName(yourName);
cout << "\nPlease enter the current year: ";
int currentYear;
getline (cin, currentYear);
myHeartrate.setCyear(currentYear);
cout << "\nYou entered " << currentYear;
}
Heartrate class:
#include <string> //enables string use
class Heartrates {
public:
void setName(std::string yourName) {
name = yourName;
}
std::string getName() const {
return name;
}
void setCyear(int currentYear) {
Cyear = currentYear;
}
int getCyear() const {
return Cyear;
}
private:
std::string name;
int Cyear{ 0 };
};
I keep running into an error that states there is no matching overload function found, yet as you can see I'm using the same structure between both the main class and the header and the name worked just fine.
The version of std::getline you are trying to use there does not accept an int as a argument. See the function marked 2 (C++11) for the function you are trying to call here. std::istringstream can be included from sstream. I would add a std::endl (or new line) to the final print out to make it appear nicer as well.
#include <iostream>
#include <sstream>
#include <string>
using namespace std;
int main() {
Heartrates myHeartrate;
cout << "Please enter your name (First and Last): ";
// read line
string line;
getline (cin, line);
// line is yourName
myHeartrate.setName(line);
// read line, read int from line
cout << "\nPlease enter the current year: ";
int currentYear;
getline (cin, line);
std::istringstream ss(line);
ss >> currentYear;
myHeartrate.setCyear(currentYear);
cout << "\nYou entered " << currentYear << endl;
return 0;
}

How can i write information words into a file with c++

Am trying to Write file into a file but once i enter the name it prompts a click to close
this is mine code
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
void login(){
char name, email, address;
ofstream myfile;
myfile.open ("user.dll");
cout << "Enter Name : ";
cin >> name;
cout << "Enter Email : ";
cin >> email;
cout << "Enter Address : ";
cin >> address;
myfile <<name << email << address << endl;
}
int main()
{
login();
system("pause");
return(0);
}
and the is the display
You should be entering std::strings not chars. Change
char name, email, address;
To
string name, email, address;
Why did it seemingly skip your 2nd and 3rd cin prompts?
You used std::cin to read the input from the stream. During the first prompt, you entered "chrys", which added 5 chars to the stream.
If you followed the operations of cin you basically had:
name = 'c'
email = 'h'
address = 'r'
If you would have used getch() for example, this would have been obvious. If you were set on char you would have had to use the C-like method of reading into a char[], but since this is C++, std::string is a much better option for your case.

Dynamic parametrized constructor issue in C++

I am here including a simple program that written in C++ where I am trying to use a parametrized constructor. My idea is to instantiate the class dynamically and capture the required task.
But whenever I run the program and enter the task 1 it simply prints the two lines (i.e. Enter Name.Enter Tel.No.). It is actually supposed to print "Enter Name." then input the name, And then again print "Enter Tel.No.".
How can I fix the issue? I have to use parametrized constructor dynamically while creating an object.
#include <iostream>
#include <conio.h>
#include <fstream>
#include <string>
using namespace std;
class myClass
{
string fullname,telephone;
public:
myClass(int taskType = 2)
{
if(taskType==1)
{
add_record();
}
else if(taskType==2)
{
//view_records();
}
else if(taskType==3)
{
//delete_record();
}else{
// custom_error();
}
}
void add_record()
{
cout << "Enter Name.\n";
getline(cin, fullname);
cout << "Enter Tel. No.\n";
getline(cin, telephone);
}
};
main (){
int myTask;
cout << "Enter a Task-Type. \n"
<< "1 = Add Record,"
<< "2 = View Records,"
<< "3 = Delete a Record\n\n";
cin >> myTask;
myClass myObject(myTask);
getch();
}
You are using cin >> myTask to read the first input. As you press enter to give the 1, selecting "Add Record", that 1 will be read from the buffer, but your newline will still be in the input buffer. Thus, the first getline will only read this off the buffer, producing an empty input for the line getline(cin, fullname);
The reason is that the first newline after the task type is not consumed by
cin >> myTask
so the fullname reading will only read an empty line and the "enter Tel.No" thing will be printed directly.
Insert a getline call after the cin >> myTask to fix this problem.
Also see this question.
This probably has nothing to do with your constructor, but rather with the mixing of cin >> and getline. Add a getline to a garbage variable after cin >> myTask and it should work.