when i run the code, the output is my first and
last name and that's it.
I've used cin.clear, cin.sync and cin.ignore.
None of these seemed to work. However, when i used
cin.fail, why did this work?
#include<iostream>
#include<string>
using namespace std;
int main()
{
string str_mystr;
cout << "What is your name? ";
getline (cin, str_mystr, '#');
cout << "Hello " << str_mystr << '\n';
// cin.ignore();
cout << "What is your favorite city? ";
getline (cin, str_mystr);
cout << "I like " << str_mystr << '\n';
return 0;
}
just do what you did for name
#include<iostream>
#include<string>
using namespace std;
int main()
{
string str_mystr;
cout << "What is your name? ";
getline (cin, str_mystr, '#');
cout << "Hello " << str_mystr << '\n';
// cin.ignore();
cout << "What is your favorite city? ";
getline (cin, str_mystr,'#');
// ^^^^
cout << "I like " << str_mystr << '\n';
return 0;
}
adding '#' will do the work just fine
Related
#include <iostream>
#include <string>
#include <vector>
using namespace std;
//void FillNames(vector<string> & vecNames);
//void SortNames(vector<string> & vecNames);
int main() {
string firstName;
int i = 0;
cout << "Information:" << endl;
cout << "EOF character in windows is Control + Z" << endl;
cout << "and EOF character on Mac is Control + D:" << endl;
cout << "-----------------------------------------------" << endl;
while (i < 13) {
cout << "Enter first name only in all caps (example: JOHN)" << endl;
cout << "Enter EOF character to exit name entry: ";
cin >> firstName;
i++;
}
}
Here is a link to what i'm trying to accomplish.
https://drive.google.com/file/d/1AuW9hQPbd1f294dCZN6Q8Ac6lgIy0Ivf/view?usp=sharing
You can use the stream's input state to break the loop when EOF is entered:
while (i < 13) {
cout << "Enter first name only in all caps (example: JOHN)" << endl;
cout << "Enter EOF character to exit name entry: ";
if (cin >> firstName)
i++;
else
break;
}
After my first entry, my second entery name field fills up with the input buffer from the previous entry. Why? I am even using the getline but the problem still persists. Please help me with the problem. This is question from Jumping Into C++ book .
#include <iostream>
#include <string>
using namespace std;
struct Person
{
string name;
string address;
long long int PhoneNumber;
};
void displayEntries(Person p[])
{
int enteryNumber;
cout << "Enter the entry number of the person for details(enter 0 to display all entries): ";
cin >> enteryNumber;
if(enteryNumber == 0)
{
for(int i = 0; i < 10; i++)
{
cout << "Entery Number: " << i + 1;
cout << "Name: " << p[i].name << endl;
cout << "Address: " << p[i].address << endl;
cout << "Phone Number: " << p[i].PhoneNumber << endl;
}
}
do
{
cout << "Entery Number: " << enteryNumber;
cout << "Name: " << p[enteryNumber].name << endl;
cout << "Address: " << p[enteryNumber].address << endl;
cout << "Phone Number: " << p[enteryNumber].PhoneNumber << endl;
} while (enteryNumber != 0);
}
int main()
{
Person p[10];
for(int i = 0; i < 10; i++)
{
cout << "Enter the details of the person\n\n";
cout << "Name: ";
getline(cin, p[i].name);
cout << "Address: ";
getline(cin, p[i].address);
cout << "Phone Number: ";
cin >> p[i].PhoneNumber;
cout << endl;
}
displayEntries(p);
return 0;
}
You can see what is happening when you read the reference for getline:
When used immediately after whitespace-delimited input, e.g. after
int n;
std::cin >> n;
getline(cin, n); //if used here
getline consumes the endline character left on the input stream by operator>>, and returns immediately. A common solution is to ignore all leftover characters on the line of input with
cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
before switching to line-oriented input.
cin >> p[i].PhoneNumber; only gets the number. That leaves the line ending still in the input buffer to be read the next time you try to read a line.
I have just started C++ after working with C for almost a year. I'm writing a program for a user to input info about a song. I read that I should use getline() to read strings with spaces. Here is my code:
#include <string>
#include <cstring>
#include <iostream>
using namespace std;
int main()
{
typedef struct Song
{
char title[20];
char album[20];
char artist[20];
int year;
} song;
//store song info
Song Input;
char inputStr[20];
int inputYear;
cout << "Enter the name of a song: ";
getline(cin, inputStr);
strcpy(Input.title, inputStr);
cout << "Enter the album of your song: ";
getline(cin, inputStr);
strcpy(Input.album, inputStr);
cout << "Enter the artist of your song: ";
getline(cin, inputStr);
strcpy(Input.artist, inputStr);
cout << "Enter the year your song was released: ";
cin >> inputYear;
Input.year = inputYear;
//print
cout << "Song title: " << Input.title << endl;
cout << "From album: " << Input.album << endl;
cout << "Artist: " << Input.artist << endl;
cout << "Released: " << Input.year << endl;
return 0;
}
My compiler1 throws 3 errors, one for each of the getline() calls, not recognizing getline() despite the fact I have #include <string>. I have looked up sample usage of the getline() function.
Thanks for any help.
1I have wondered if this problem might concern an issue with the standard of C++ that my compiler supports. I did a bit of research and I did not find anything that helped me learn which standard I am using. Here's some info:
I'm using Terminal on Mac.
After g++ version:
Configured with: --prefix=/Applications/Xcode.app/Cont.../usr/include/c++/4.2.1
Apple LLVM version 8.1.0 (clang-802.0.42)
These lines seem to be the only ones of use here, but I could give more info. If someone has any idea which standard of C++ this is, whether it's C++11, or C++14, or otherwise, that would also be very helpful. Thanks again.
UPDATE:
started from scratch, tried to take as much of your advice as possible while still sticking to some of what I know. No errors and works just as I hoped. Thanks for all your help.
New code:
#include <string>
#include <cstring>
#include <iostream>
using namespace std;
struct Song
{
string title;
string artist;
string album;
string year;
}song;
int main()
{
Song Input;
cout << "Song? ";
getline(cin, Input.title);
cout << "Artist? ";
getline(cin, Input.artist);
cout << "Album? ";
getline(cin, Input.album);
cout << "Year? ";
getline(cin, Input.year);
cout << "Song: " << Input.title << endl;
cout << "Artist: " << Input.artist << endl;
cout << "Album: " << Input.album << endl;
cout << "Year: " << Input.year << endl;
return 0;
}
The version of getline you are using takes a std::string as a parameter, not an array of char. If you want to use an array of char (and you shouldn't), you need to use the member function version:
cin.getline( some_char_array, array_size );
I would switch from using char arrays to using string's everywhere. For example I would do your code like this:
#include <string>
#include <iostream>
struct Song{
std::string title;
std::string album;
std::string artist;
int year;
};
int main()
{
//store song info
Song Input;
int inputYear;
std::cout << "Enter the name of a song: ";
getline(std::cin, Input.title);
std::cout << "Enter the album of your song: ";
getline(std::cin, Input.album);
std::cout << "Enter the artist of your song: ";
getline(std::cin, Input.artist);
std::cout << "Enter the year your song was released: ";
std::cin >> Input.year;
//print
std::cout << "Song title: " << Input.title << '\n';
std::cout << "From album: " << Input.album << '\n';
std::cout << "Artist: " << Input.artist << '\n';
std::cout << "Released: " << Input.year << std::endl;
return 0;
}
My preference is to not use using namespace std; but there's nothing wrong with it. Notice that using strings directly I don't need to copy things. I can use getline to do all that for me. I also don't need to worry about overrunning the size of the char array because string does that for me as well.
I am wringing a simple code to learn more about string. When I ran my code it would not print my last name. Can someone explain why? I used string phrase to store it and it only appears to have stored my first name. Here is the code.
#include <iostream>
#include <string>
#include <cstring>
using namespace std;
int main()
{
cout << "Exercise 3B" << endl;
cout << "Kaitlin Stevers" << endl;
cout << "String arrays" << endl;
cout << endl;
cout << endl;
char greeting[26];
cout << "Please enter a greeting: " << endl;
cin >> greeting;
cout << "The greeting you entered was: " << greeting << endl;
string phrase;
cout << "Enter your full name " << endl;
cin >> phrase;
cout << greeting << ", how are you today " << phrase << "?" << endl;
return 0;
}
I used string phrase to store it and it only appears to have stored my first name.
That makes sense.
cin >> phrase;
will stop reading when it encounters a whitespace character in the input.
To read the full name you can use one of the following approaches.
Use two calls to cin >>.
std::string first_name;
std::string last_name;
cin >> first_name >> last_name;
Use getline to read the entire line. getline will read everything in a a line, including whitespace characters.
getline(cin, phrase);
When you call cin >> phrase;, it only reads the string up to the first non-space character. If you want to include spaces in your name, best goes with getline(cin,phrase);.
IMPORTANT: getline() will reads whatever it is in the stream buffer up to the first \n. It means that when you enter cin >> greeting;, if you hit ENTER, getline() will read everything before that \n that is not already read, which is NOTHING into your phrase variable, making it an empty string. An easy way out is to call getline() twice. E.g.
#include <iostream>
#include <string>
#include <cstring>
using namespace std;
int main()
{
cout << "Exercise 3B" << endl;
cout << "Kaitlin Stevers" << endl;
cout << "String arrays" << endl;
cout << endl;
cout << endl;
char greeting[26];
cout << "Please enter a greeting: " << endl;
cin >> greeting; //IMPORTANT: THIS ASSUME THAT GREETING IS A SINGLE WORD (NO SPACES)
cout << "The greeting you entered was: " << greeting << endl;
string phrase;
cout << "Enter your full name " << endl;
string rubbish_to_be_ignored;
getline(cin,rubbish_to_be_ignored); //this is going to read nothing
getline(cin, phrase); // read the actual name (first name and all)
cout << greeting << ", how are you today " << phrase << "?" << endl;
return 0;
}
Assuming you store that code in the file stackoverflow.cpp. Sample run:
Chip Chip#04:26:00:~ >>> g++ stackoverflow.cpp -o a.out
Chip Chip#04:26:33:~ >>> ./a.out
Exercise 3B
Kaitlin Stevers
String arrays
Please enter a greeting:
Hello
The greeting you entered was: Hello
Enter your full name
Kaitlin Stevers
Hello, how are you today Kaitlin Stevers?
Tested on ubuntu 14.04
I'm having some minor trouble with this basic C++ quiz program. In the main function, I have the user enter his/her name and I pass this string to the next function, take_quiz. However, I've noticed that if I include a name with a space in it (like a first and last name), an error occurs. For some reason, the amount of letters in the second word produces the same amount of displays of, "Please enter a valid answer (a, b, c, d)." I thought this was strange because that prompt can only occur when the inline function valCheck is used which is after the first cin of a variable in take_quiz. I need some help identifying the issue and correcting it. Thanks!
inline char valCheck(char& input)
{
tolower(input);
while(input < 97 || input > 100)
{
cout << "Please enter a valid answer (a, b, c, d):" << endl;
cin >> input;
}
}
int main(int argc, char *argv[])
{
string name;
cout << "This program will quiz your knowledge of C++. Please enter your name:" << endl;
cin >> name;
cout << "Hello " << name << "! IT'S QUIZ TIME!!!" << endl;
take_quiz(name);
system("PAUSE");
return EXIT_SUCCESS;
}
void take_quiz(string name2)
{
char quiz_results[10];
system("PAUSE");
cout << "\nThe quiz will now begin.\nThis quiz covers topics such as data types, arrays, pointers, etc." << endl
<< "To answer the multiple choice questions,\nsimply input a, b, c, or d according to the given options." << endl
<< "The test will continue regardless if you enter a question wrong or right." << endl
<< "Good luck " << name2 << "!" << endl;
system("PAUSE");
cout << "\n1. What preprocessor command must one include to use the cout and cin function?" << endl
<< "\na. #include <iomanip>" << endl
<< "b. #include <iostream>" << endl
<< "c. #include <cmath>" << endl
<< "d. using namespace std;" << endl;
cin >> quiz_results[0];
valCheck(quiz_results[0]);
Your valCheck() doesn't return anything - according to signature it needs to return a char value. You want to use std::getline(std::cin, str); instead of std::cin if your string contains newlines. std::cin will by default skip whitespaces. Also you're invoking take_quiz() without a prototype function before, so you need to move it above main() or specify the function signature at least above.
The complete program should look like this (you just need to add a check if quiz_results[0] is equal to 'b').
#include <iostream>
#include <string>
using namespace std;
inline char valCheck(char& input){
tolower(input);
while (input < 97 || input > 100){
cout << "Please enter a valid answer (a, b, c, d):" << endl;
cin >> input;
}
return input;
}
void take_quiz(string name2)
{
char quiz_results[10];
system("PAUSE");
cout << "\nThe quiz will now begin.\nThis quiz covers topics such as data types, arrays, pointers, etc." << endl
<< "To answer the multiple choice questions,\nsimply input a, b, c, or d according to the given options." << endl
<< "The test will continue regardless if you enter a question wrong or right." << endl
<< "Good luck " << name2 << "!" << endl;
system("PAUSE");
cout << "\n1. What preprocessor command must one include to use the cout and cin function?" << endl
<< "\na. #include <iomanip>" << endl
<< "b. #include <iostream>" << endl
<< "c. #include <cmath>" << endl
<< "d. using namespace std;" << endl;
cin >> quiz_results[0];
valCheck(quiz_results[0]);
}
int main(int argc, char *argv[]){
string name;
cout << "This program will quiz your knowledge of C++. Please enter your name:" << endl;
std::getline(std::cin, name);
cout << "Hello " << name << "! IT'S QUIZ TIME!!!" << endl;
take_quiz(name);
system("PAUSE");
return EXIT_SUCCESS;
}
I changed how to get string input from User
int main(int argc, char *argv[])
{
char name[100];
cout << "This program will quiz your knowledge of C++. Please enter your name:" << endl;
cin.getline(name,sizeof(name));
//cin >> name;
cout << "Hello " << name << "! IT'S QUIZ TIME!!!" << endl;
take_quiz(name);
system("PAUSE");
return EXIT_SUCCESS;
}