This question already has answers here:
Removing trailing newline character from fgets() input
(14 answers)
Closed 5 years ago.
#include<iostream>
using namespace std;
int main()
{
char str[10] = "Anmol" ;
int age = 17 ;
cout << "Enter your name here :- " ;
fgets(str, sizeof(str), stdin) ;
cout << "Enter your age here :- " ;
cin >> age ;
cout << "Hello World, It's " << str << "And my age is " << age ;
return 0 ;
}
On running the code, the compiler is giving output in different line like:-
fgets() is a file function which is used to read text from keyboard, as in “file get string.”
fgets() function is read the string as well as "enter" character ascii code which is 13 (carriage return - CR) .so the above code consider the CR character at the end of the 'str' that's why it print in the next line .
You can use the gets_s() function to take the string from the keyboard.
Try the below code .
#include<iostream>
using namespace std;
int main()
{
char str[10] = "Anmol";
int age = 17;
cout << "Enter your name here :- ";
gets_s(str);
cout << "Enter your age here :- ";
cin >> age;
cout << "Hello World, It's " << str << " And my age is " << age;
return 0;
}
try replace '\r\n', and '\n\r' with '' in str
look at here for replace in string : How to replace all occurrences of a character in string?
Try this:
#include <iostream>
#include <string>
using namespace std;
int main()
{
string str;
int age;
cout << "Enter your name here :- " ;
cin >> str;
cout << "Enter your age here :- " ;
cin >> age ;
cout << "Hello World, It's " << str
<< " And my age is " << age << endl;
return 0 ;
}
When you use fgets(), you also get the ending newline character in the input. That explains your output. You could use std::getline to avoid that problem.
int main()
{
std::string str = "Anmol" ;
int age = 17 ;
cout << "Enter your name here :- " ;
std::getline((std::cin, str) ;
cout << "Enter your age here :- " ;
cin >> age ;
cout << "Hello World, It's " << str << " and my age is " << age << std::endl;
return 0 ;
}
Related
This question already has answers here:
cin and getline skipping input [duplicate]
(4 answers)
Why does std::getline() skip input after a formatted extraction?
(5 answers)
Closed 21 days ago.
#include <iostream>
using namespace std;
int main(){
//set variables
string name1;string name2;string name3;string n1;string n2;string n3;
int age1; int age2; int age3;
//get names and ages
cout << "Who Is The First Student?"<< endl;
getline(cin, name1); //name 1
cout << "What is " << name1<< "'s Age?"<< endl;
cin >> age1; // age 1
cout << "Who Is The Second Student?"<< endl;
getline(cin, name2); //name 2
cout << "What is " << name2<< "'s Age?"<< endl;
cin >> age2; //age 2
cout << "Who Is The Third Student?"<< endl;
getline(cin, name3); // name 3
cout << "What is " << name3<< "'s Age?"<< endl;
cin >> age3; //age 3
// gets modified names
n1 = name1.substr(2, name1.size() -3);
n2 = name2.substr(2, name2.size() -3);
n3 = name3.substr(2, name3.size()-3);
// Output formatting
cout << "Name Age Modified"<<endl;
cout << name1<< " "<<age1<<" "<<n1<<endl;
cout << name2<< " "<<age2<<" "<<n2<<endl;
cout << name3<< " "<<age3<<" "<<n3<<endl;
return 0;
}
The output asks the first question which is for the name of the first student but it outputs as this:
Who Is The First Student?-
John Doe-
What is John's Age?-
19-
Who Is The Second Student?-
What is 's Age?-
It is skipping the user input of the second student's name and instantly asking for the age but I don't know why this is happening, is there something wrong with my code or do I have the formatting incorrect? I believe that I used the getline function correctly but I may be incorrect and unaware of it being skipped over by a more important function.
The std::string::substr() man page says this about the exception you are seeing:
Parameters
pos - position of the first character to include
count - length of the substring
Exceptions
[throws] std::out_of_range if pos > size()
The main problem of the program is that the operator >> reads only one word.
That is for example in these statements
cout << "Who Is The First Student?"<< endl;
cin >> name1; //name 1
You entered a string that contains two words "John Doe". But the operator >> reads only the first word "Jphn" in the variable name1.
So in the next input statement
cout << "What is " << name1<< "'s Age?"<< endl;
cin >> age1; // age 1
an error occurred because instead of a number the input buffer contains the word "Doe".
So as a result the variables name1, name2, and name3 do not contain what you are expecting. And these statements
n1 = name1.substr(2, name1.size()-3);
n2 = name2.substr(2, name2.size()-3);
n3 = name3.substr(2, name3.size()-3);
produce the run-time error.
Instead of the operator >> you should use standard function std::getline.
Here is a demonstration program based on the code of your program that shows what is the reason of the error
#include <iostream>
#include <string>
int main()
{
std::string name1, name2;
int age1;
//get names and ages
std::cout << "Input 3 Names Below:" << std::endl;
std::cout << "Who Is The First Student?" << std::endl;
std::cin >> name1; //name 1
std::cout << "What is " << name1 << "'s Age?" << std::endl;
std::cin >> age1; // age 1
std::cout << "Who Is The Second Student?" << std::endl;
std::cin >> name2; //name 2
std::cout << "name1 = " << name1 << '\n';
std::cout << "name2 = " << name2 << '\n';
}
The program output is
Input 3 Names Below:
Who Is The First Student?
John Doe
What is John's Age?
Who Is The Second Student?
name1 = John
name2 =
As you can see due to the error of reading a data in the variable age1 (the buffer contains the string "Doe") the object name2 is empty. So if you will use it in this statement
n2 = name2.substr(2, name2.size()-3);
then the runtime error will occur.
Here is another demonstration program that shows how the standard function std::getline can be used in your program.
#include <iostream>
#include <string>
#include <limits>
int main()
{
std::string name1, name2, name3;
int age1, age2, age3;
//get names and ages
std::cout << "Input 3 Names Below:" << std::endl;
std::cout << "Who Is The First Student?" << std::endl;
std::getline( std::cin, name1 ); //name 1
std::cout << "What is " << name1 << "'s Age?" << std::endl;
std::cin >> age1; // age 1
std::cin.ignore( std::numeric_limits<std::streamsize>::max(), '\n' );
std::cout << "Who Is The Second Student?" << std::endl;
std::getline( std::cin, name2 ); //name 2
std::cout << "What is " << name2 << "'s Age?" << std::endl;
std::cin >> age2; //age 2
std::cin.ignore( std::numeric_limits<std::streamsize>::max(), '\n' );
std::cout << "Who Is The Third Student?" << std::endl;
std::getline( std::cin, name3 ); // name 3
std::cout << "What is " << name3 << "'s Age?" << std::endl;
std::cin >> age3;
std::cout << "name1 = " << name1 << '\n';
std::cout << "name2 = " << name2 << '\n';
std::cout << "name3 = " << name3 << '\n';
}
The program output is
Input 3 Names Below:
Who Is The First Student?
John Dow
What is John Dow's Age?
20
Who Is The Second Student?
Mary Poppins
What is Mary Poppins's Age?
21
Who Is The Third Student?
Bob Fisher
What is Bob Fisher's Age?
25
name1 = John Dow
name2 = Mary Poppins
name3 = Bob Fisher
I want to validate the input age with the code I wrote below
cout << "Enter the Age of The " << qty << " Passenger(s) :: ";
for (int i = 1; i <= qty; i++) {
cout << "\nAge for Passenger " << i << " :: ";
cin >> age[i];
while ((!(cin >> age[i])) || (age[i]<=0)) {
// Explain the error
cout << "Error: Enter a valid age for Passenger " << i << " : ";
// Clear the previous input
cin.clear();
// Discard previous input
cin.ignore(123, '\n');
}
}
But, there is a problem. The program will stop running when I enter the age inside the range.
So, I want to ask is there any effective way to validate the age input.
Consider using std::getline and std::stringsstream. So you are just reading line and then trying to parse it.
For example:
#include <iostream>
#include <sstream>
int main(int argc, const char * argv[])
{
int qty = 10;
int* age = new int[11];
std::cout << "Enter the Age of The " << qty << " Passenger(s) :: ";
for (int i = 1; i <= qty; i++) {
std::cout << "\nAge for Passenger " << i << " :: ";
std::string s;
std::getline(std::cin, s);
std::stringstream stream(s);
while ((!(stream >> age[i])) || (age[i]<=0)) {
// Explain the error
std::cout << "Error: Enter a valid age for Passenger " << i << " : ";
std::getline(std::cin, s);
stream = std::stringstream (s);
}
}
for (int i = 1; i <= qty; i++) {
std::cout << age[i];
}
delete [] age;
return 0;
}
Also note, that it is bad pattern to use using namespace std and indexation from 1
I am the beginner of C++, just start to learn struct.
I create the struct and read the data from a file.
Here is my file:
John Smith 26832904 1657 Commerce st Flushing NY 11204 7183942833 company01 962 51
I successfully input the data to the struct. The output is perfect but just having a zero at the end, which can drive me crazy.
This is my entire code:
#include<iostream>
#include<string>
#include<fstream>
#include<iomanip>
using namespace std;
struct nametype
{
string first;
string last;
};
struct addresstype
{
string address1;
string address2;
string address3;
string city;
string state;
string zip;
};
struct contacttype
{
string home;
string person;
};
struct employeeType
{
nametype name;
string id;
addresstype address;
contacttype contact;
string worklocate;
double basewage;
int carsale;
};
int main()
{
ifstream infile;
infile.open("employeeInfor.txt");
if (!infile)
{
cout << "Error." << "\n";
}
employeeType employee;
employee.basewage = 0.0;
employee.carsale = 0;
infile >> employee.name.first >> employee.name.last
>> employee.id
>> employee.address.address1 >> employee.address.address2
>> employee.address.address3 >> employee.address.city
>> employee.address.state >> employee.address.zip
>> employee.contact.home >> employee.contact.person
>> employee.worklocate
>> employee.basewage >> employee.carsale;
cout << employee.name.first <<" "<<employee.name.last
<< " " << employee.id
<< " " << employee.address.address1 << " " << employee.address.address2
<< " " << employee.address.address3 << " " << employee.address.city
<< " " << employee.address.state << " " << employee.address.zip
<< " " << employee.contact.home << " " << employee.contact.person
<< " " << employee.worklocate
<< " " << employee.basewage << " " << employee.carsale << "\n";
infile.close();
system("pause");
return 0;
}
I output the data. That's what I got:
The end of the extra 0 is not my expectation.
By the way. I want to put the struct within the array. To make this function work for more than one employee. I know should be create the struct like, employeeType employees[5];
I just stuck from reading the file. Can't keep moving.
You try to read 14 values, but your input file contains only 13. So the last value you output, employee.carsale is 0 as in the initialization.
You read 14 parameters but your file only provides 13. Maybe you forgot to add a column in employeeInfor.txt.
#include <iostream>
#include <string>
int main(void)
{
using std::cout;
using std::cin;
using std::string;
string name;
int n1, n2;
cout << "What is your name ?\n";
cin >> name;
cout << "Hello " << name.c_str() <<"!\n"
<< "Please give me two number separated by space\n";
cin >> n1 >> n2;
cout << "Sum of " << n1 << " + " << n2 << " is " << n1 + n2 << "\n";
return 0;
}
My console input/output looks like this:
What is your name ?
John Titor
Hello John!
Please give me two number separated by space
Sum of 0 + 1961462997 is 1961462997
It doesn't print the full name, only "John", and it doesn't even ask me about puting two numbers.
You should use std::getline to get a string with spaces. std::cin separates the strings by spaces.
getline(cin, name);
In addition, you can print a std::string by std::cout without .c_str():
cout << name;
#include <iostream>
#include <string>
using namespace std;
int main() {
double age;
double months;
string name;
months = age*12.0;
cout << "Enter your name and age: ";
cin >> name >> age;
cout << "Hello " << name << " age " << age << " (" << months << " months)\n";
return(0);
}
The program asks for name and age, and should out put the name and age in a sentence with the age in months in parentheses.
Output gives something like:
Hello Bob age 20 (1.82561e-313 months), but should be Hello Bob age 20 (240 months). I did not use int because I wanted to be able to input non int values for age.
I have tried 12 instead of 12.0 and tried declaring a variable and doing months = age*m where m = 12.0 but is result is the same. By the way, the random value is about the same regardless of what variable age is. Why is this happening? Also, would this be a link-time error or run-time error?
You're doing the multiplication using age before it's initialized. What value would you expect it to give you?
Change your code to first get the age, and then do the multiplication:
cout << "Enter your name and age: ";
cin >> name >> age;
months = age*12.0;
cout << "Hello " << name << " age " << age << " (" << months << " months)\n";
Move the calculation of months to after the point age is entered (age was uninitialised in the original code):
cout << "Enter your name and age: ";
cin >> name >> age;
months = age*12.0;
cout << "Hello " << name << " age " << age << " (" << months << " months)\n";