If I ask a user for an input that's separated by dashes, how can I store them into multiple variables? One for each part that is separated by the dashes.
for example, this doesn't work.
cout << "enter date" << endl;
// user inputs something like 11/11/1980
cin >> month
I understand the input is stored in the iostream but how can I store whats after the first slash
I think that you should look into using the date tools that C++11 already provides to you.
time.h's struct tm has it's own streaming operators. So I'd do something like this:
#include <iostream>
#include <sstream>
#include <iomanip>
#include <ctime>
using namespace std;
int main() {
tm t;
istringstream ss("11/11/1980");
ss >> get_time(&t, "%m/%d/%Y");
cout << t.tm_mon + 1 << ' ' << t.tm_mday << ' ' << t.tm_year << endl;
return 0;
}
I don't know why but it's noteworthy that tm.tm_mon is 0-based...
See also: http://en.cppreference.com/w/cpp/io/manip/put_time
I just got into the same situation, and I found this works.
Hope this is still useful.
#include <iostream>
#include <string>
#include <iomanip>
int main()
{
// This is to initialize variables:
std::string mm,dd,yy;
// Now get the input
std::cout << "Enter the Date number: ";
// Then split it using std::getline() with delimiter '/'
// and assign them to relevant variables
std::getline(std::cin, mm,'/');
std::getline(std::cin, dd, '/');
std::cin >> yy;
std::cout << mm << " " << dd << " " << yy;
}
you can store input in string (or char array) and then later separate you desired parts, for that purpose you can create a function which will take the input string as parameter and separate its parts.
You could search the web for "c++ read date" for some examples.
One method is:
unsigned int month;
unsigned int day;
unsigned int year;
char separator;
cin >> month >> separator >> day >> separator >> year;
But there are issues with that, such as having a space before the '/'.
Another method is to fscanf with a decent format string:
fscanf(stdin, "%2d/%2d/%4d", &month, &day, &year);
but, that doesn't use the C++ streams.
You could use strings and getline:
std::string month_str;
std::string day_str;
std::string year_string;
std::getline(cin, month_str, '/');
std::getline(cin, day_str, '/');
std::getline(cin, year_str); // What's the delimiter here???
Related
Question may seem like a duplicate but I have researched and found nothing that would actually answer my question.
So I have a task that let's the user input groceries as a string, the weight and price as doubles. Simple enough, right? Well, the problem is that the user will enter it in the following format:
Enter product 1: Potato; 5 kg; 49 kr;
Enter product 2: Carrot; 0.5 kg; 13 kr;
Enter product 3: Onion; 0.1 kg; 2 kr;
And then the products will be sorted in a specific manner. However that is not what I need help with, I have a problem with reading in only "Potato", "5" and "49" and store them in seperate variables.
#include <iostream>
#include <iomanip>
#include <vector>
#include <algorithm>
using namespace std;
struct Product_Type
{
string name;
double weight;
double price;
};
void get (Product_Type & p)
{
cin >> p.name;
cin.ignore(1);
cin >> p.weight;
cin.ignore(2);
cin >> p.price;
cin.ignore(2);
}
If I do it like this, I will store "Potato;" and not "Potato" in my name variable. So my question is how do I manipulate a string to only read to a certain index and store the content in a variable? I don't want to read the actual semi-colons. Is there a simple way to do this?
You need to understand how formatted input and unformatted input works.
Please read here about it.
You do not need ignore at all. You can do all with simple statements.
But the precondition is that the input matches your specification. Any input of wrong data leads to a problem. So, let's assume that the input follows the above pattern. OK.
Regarding your problem, where you read "potato;" instead of "potato". This is because you use a formatted input function >> to read a string. And this function will stop, if it sees a white space and not before. It will also ignore leading white space by default, but that is not important here.
To solve the problem to read a string until a certain delimiter, you can use the unformatted input function std::getline. Please see here.
So, to get the name, you may write std::getline(std::cin, p.name, ';');. This will read the name from the input stream, including the semicolon, but store the pure name, without the semicolon in the string.
Next we are talking about reading 5 kg; 49 kr. We want to have the "weight". We can simply use formatted input function >> to get it. There is a white space after that, so, very simple. You can write std::cin >> p.weight; to get it.
Next we have to read kg; 49 kr. So, we will use a dummy string and with that can read the "kg;" which we do simple not use. So, with a dummy string "s1", we can write std::cin >> s1;. The kg; will be gone from the stream.
Now we see 49 kr;. Reading the price is again simple using >>. We will write std::cin >> p.price; and have it.
Last but not least we need to read the rest of the line, including the enter. For that we use again std::getline. No need to specify any delimiter, because the standard delimiter is already '\n'.
Then the full code looks like the below:
#include <iostream>
#include <string>
struct Product_Type
{
std::string name;
double weight;
double price;
};
void get(Product_Type& p)
{
std::string s1, s2;
std::getline(std::cin, p.name, ';');
std::cin >> p.weight;
std::cin >> s1;
std::cin >> p.price;
std::getline(std::cin, s2);
}
int main() {
Product_Type pt;
get(pt);
std::cout << pt.name << " --> " << pt.weight << " --> " << pt.price << '\n';
return 0;
}
But this is not considered to be good. There may be errors in the input and with that the failbit of std::cin would be set and you cannot continue to read.
Therefore, normally, we would read first the complete line with std::getline which will most likely always work. Then, we "convert" the string to a stream using an std::istringstream to be able to extract the data from there. If the complete line has an error, then only the temporary std::istringstream will be gone. So this approach is a little bit more robust.
This could then look like:
#include <iostream>
#include <string>
#include <sstream>
struct Product_Type
{
std::string name;
double weight;
double price;
};
void get(Product_Type& p)
{
std::string line, s1, s2;
std::getline(std::cin, line);
std::istringstream iss(line);
std::getline(iss, p.name, ';');
iss >> p.weight;
iss >> s1;
iss >> p.price;
std::getline(iss, s2);
if (not iss)
std::cerr << "\nError: Problem with input\n\n";
}
int main() {
Product_Type pt;
get(pt);
std::cout << pt.name << " --> " << pt.weight << " --> " << pt.price << '\n';
return 0;
}
And a little bit more advanced with chaining the io-functions, we can write
#include <iostream>
#include <string>
#include <sstream>
struct Product_Type
{
std::string name;
double weight;
double price;
};
void get(Product_Type& p)
{
std::string line, s1, s2;
std::getline(std::cin, line);
std::istringstream iss(line);
std::getline(std::getline(iss, p.name, ';') >> p.weight >> s1 >> p.price, s2);
if (not iss)
std::cerr << "\nError: Problem with input\n\n";
}
int main() {
Product_Type pt;
get(pt);
std::cout << pt.name << " --> " << pt.weight << " --> " << pt.price << '\n';
return 0;
}
All the above is very simplified, but may give you a starting point for better ideas.
#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.
#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.
#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.
#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.