如何使用 cin.ignore 忽略 C++ 中的指定字符

how to use cin.ignore to ignore specified character in C++

我想使用 cin.ignore() 从键盘获取数据。 示例:我输入一个字符串“12/12/2015”。我怎么能忽略“/”来让我的数据像“12122015”这样的字符串。因为我读过书(如何编程c++,deitel),他们使用cin.ignore来做到这一点,但现在我不能找出它在哪里? 感谢您的帮助!!!

您必须手动处理它

cin.ignore 以另一种方式工作。 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.

可能是简单的解决方案:Replace\remove character in string

你可以读取固定数量的字符,然后使用cin.ignore(1)跳过后面的字符,但不是很优雅。如果我是你,我会使用 getline,并将行尾定界符设置为 '/':

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';

但是,如果你真的想使用cin.ignore,方法如下(我想,有一段时间没用过C字符串了,似乎给了权利结果):

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';