有没有办法在获取数组的用户输入时忽略字符
Is there a way to ignore a char when getting user input for array?
in C++ 我正在创建一个程序,要求用户输入以下格式的日期:月/日/年。由于日期是一个 int 并且必须是 int,我认为在一行中获取它的最合乎逻辑的方法是如果我要使用数组。
所以我创造了这样的东西...
int dateArray[3];
for (int i=0; i<3; i++)
cin >> dateArray[i];
int month = dateArray[0];
...etc
我的问题是,如果用户输入"1/23/1980",有没有办法忽略用户输入的/?
谢谢。
您可以使用
std::istream::ignore()
忽略一个字符。由于您可能只想忽略干预字符,因此您需要知道何时忽略以及何时不忽略。对于约会,我个人不会打扰,而只是阅读三个术语:
if (((std::cin >> month).ignore() >> year).ignore() >> day) {
// do something with the date
}
else {
// deal with input errors
}
我实际上也倾向于检查是否收到了正确的分离器,并且可能只是为此目的创建一个操纵器:
std::istream& slash(std::istream& in) {
if ((in >> std::ws).peek() != '/') {
in.setstate(std::ios_base::failbit);
}
else {
in.ignore();
}
return in;
}
// ....
if (std::cin >> month >> slash >> year >> slash >> day) {
// ...
}
。而且,显然,我会在所有情况下检查输入是否正确。
考虑对这种类型的解析使用 C++11 正则表达式库支持。 例如
#include <iostream>
#include <iterator>
#include <regex>
#include <string>
int main()
{
std::string string{ "12/34/5678" };
std::regex regex{ R"((d{2})/(d{2})/(d{4}))" };
auto regexIterator = std::sregex_iterator( std::begin( string ), std::end( string ), regex );
std::vector< std::string > mdy;
for( auto matchItor = regexIterator; matchItor != std::sregex_iterator{}; ++matchItor )
{
std::smatch match{ *matchItor };
mdy.push_back( match.str() );
}
const std::size_t mdySize{ mdy.size() };
for( std::size_t matchIndex{ 0 }; matchIndex < mdySize; ++matchIndex )
{
if( matchIndex != mdySize && matchIndex != 0 ) std::cout << '/';
std::cout << mdy.at( matchIndex );
}
}
我不会忽略它;它是你格式的一部分,即使你不需要无限期地保留它。
我会把它读成char
,并确保它实际上是/
.
相关文章:
- 无法在 C++ 中输入字符数组
- 当我输入字符类型的数字时,为什么我无法获得整数?
- 在不使用字符串库的情况下输入字符*
- 为什么当我输入字符时,这个特定的 cin.get() 语句在C++中不起作用?
- C++中输入字符数组的特定验证
- 如果用户在 int 中输入字符,如何使用输入
- 当我们在以下程序(C )中输入字符时,该如何解决
- 如何在结构中输入字符到向量
- 用户输入逻辑运算符符号或数字,如果输入字符或字符串则无效
- 输入字符时忽略回车键
- 在 switch 语句中输入字符以进行C++时用户输入错误
- 使用Back_inserter从任何位置的输入字符中使用Back_inserter进行过滤数组字符串
- 如何在应该显示的printf之前输入字符
- C++ 输入字符而不是 int 会导致无限循环.如何检查错误的输入
- 为什么"keep_window_open()"不等待输入字符?
- 为什么我的程序在输入字符时有一个无限循环
- 当提示输入整数值时输入字符时,为什么程序会中断
- 关闭回显后如何再次回显输入字符
- 忽略输入字符
- 从文件的单行读取输入字符