I want to use cin.ignore() to get my data from keyboard. example: I input a string "12/12/2015". How can I ignore "/" to get my data such a string as "12122015".Because I read in book (How to program c++, deitel), they used cin.ignore to do that, but now I can't find out where it is? Thanks for your helps!!!
You could read a fixed amount of characters and then use cin.ignore(1)
to skip the following character, but it is not very elegant. If I was you, I'd use getline
, and set an end-of-line delimiter to be '/'
:
string day, month, year;
getline(cin, day, '/');
getline(cin, month, '/');
// and the rest is assumed to be the year
cin >> year;
string date = day + month + year;
cout << date << '\n';
However, if you really want to use cin.ignore
, here's how (I think, haven't used C strings in a while, seems to give the right results):
char day[3], month[3], year[5];
cin.get(day, 3);
cin.ignore(1);
cin.get(month, 3);
cin.ignore(1);
cin.get(year, 5);
string date = string(day) + string(month) + string(year);
cout << date << '\n';
-
thanks a lot, your explanation help me very much, but I am constructing a date class and I want to allow the user to input a string mm/dd/yyyy in the console windows instead of inputting dd, then mm and then yyyy. At this point I have problem with dividing the string to get my data "ddmmyyyy". do you have any idea – Baohq Aug 23 '15 at 2:24
-
You have to process it manually
cin.ignore works another way. See cplusplus
istream& ignore (streamsize n = 1, int delim = EOF);
Extracts characters from the input sequence and discards them, until either n characters have been extracted, or one compares equal to delim.
May be as trivial solution:Replace\remove character in string
-
i have read this syntax in the internet, but i don't know how to apply it in my problem – Baohq Aug 23 '15 at 2:29
istream::ignore
ignores characters based on their position. Not their content. – Drew Dormann Aug 21 '15 at 17:57