using strings in c++ and cygwin -
using strings in c++ and cygwin -
im new @ need little help. want allow input many characters , spaces neccesary fill input, example, typed cin>>name , cin>>birthday if person types first , lastly name skip next cin function. how avoid this, want able declare name sort of string or char without having go through whole name=first+last ordeal , having them input first , last..if gets im saying need header file , proper declarations..im new @ im sure sick understand complex answers might get
use std::getline input on 1 line.
std::string name; std::getline(std::cin, name);
alternatively, if expect birthday on same line, this.
std::string input; std::getline(std::cin, input); std::istringstream input_stream(input); std::string first_name, last_name, birthday; if (!(input_stream >> first_name)) std::cout << "input cannot empty.\n"; if (!(input_stream >> last_name)) std::cout << "you must have lastly name.\n"; if (!(input_stream >> birthday)) std::cout << "you forgot birthday.\n";
if birthday contains spaces in it, can utilize std::getline on remaining words in stream.
std::getline(input_stream, birthday);
so programme becomes:
#include <iostream> #include <sstream> int main() { std::string input; std::getline(std::cin, input); std::istringstream input_stream(input); std::string first_name, last_name, birthday; if (!(input_stream >> first_name)) std::cout << "input cannot empty.\n"; if (!(input_stream >> last_name)) std::cout << "you must have lastly name.\n"; input_stream.ignore(); // discard space doesn't extracted out std::getline(input_stream, birthday); std::cout << first_name << "\n"; std::cout << last_name << "\n"; std::cout << birthday; }
in order discard space that's left in stream, utilize input_stream.ignore();
.
if want handle names have spaces in it, apply same principle. time have supply arguments ignore tell discard spaces.
int main() { std::string input; std::getline(std::cin, input); std::istringstream input_stream(input); std::string first_name, last_name, birthday; std::getline(input_stream, first_name, ','); input_stream.ignore(1, ' '); // discard space std::getline(input_stream, last_name, ','); input_stream.ignore(1, ' '); // discard space std::getline(input_stream, birthday, ','); std::cout << first_name << "\n"; std::cout << last_name << "\n"; std::cout << birthday; }
example run:
class="lang-none prettyprint-override">first name, lastly name, birthday first name lastly name birthday
c++ string char cin
Comments
Post a Comment