如何在c++中强制用户以格式化的方式输入
How to force the user to input in a formatted way in c++
我应该强制用户输入一个数字,然后输入一个空格,然后输入字符串,如果格式错误,我应该终止程序。当我使用cin时,编译器忽略了空格,并认为字符串的第一个字符是他应该检查的字符,以确保用户输入了空格,因为第一个字符总是不是空格,所以他终止了。我该怎么办?!
我假设"当我使用cin时"是指>>
运算符。使用>>
读取istream
是一个格式的输入函数,这意味着输入是预先格式化的,其中一个效果是默认跳过空白。
有几种方法可以解决您的问题,包括一次读取单个字符(使用未格式化的输入函数,如std::istream::get
),或者一次读取一行并解析该行。
或者,您可以使用noskipws
操纵器关闭空白字符的跳过:
#include <iostream>
#include <string>
int main()
{
int num;
char c;
std::string str;
if (std::cin >> std::noskipws >> num >> c >> str && c == ' ')
std::cout << "ok" << std::endl;
else
std::cout << "Failed" << std::endl;
}
使用std::getline
。如果你需要进一步的帮助,一定要发布一个演示问题的代码示例,否则你不会得到具体的答案。
示例:
#include <string>
#include <iostream>
int main()
{
std::string input;
std::cout << "Please enter a number and a string, separated by a space:";
std::getline(std::cin, input);
// Code to validate input
}
相关文章:
- 如何在c++中为模板函数实例创建快捷方式
- 在c代码之间共享数据的最佳方式
- 在C++中将函数压缩为两种方式
- C++格式化输出问题
- 以螺旋方式打印矩阵的程序.(工作不好)
- 为字符串中每 N 个字符插入空格的函数没有按照我认为的方式工作?
- 创建引用向量的优雅方式
- Constexpr替代了新的放置方式,可以让内存中的对象保持未初始化状态
- 使用QQuickFramebufferObject时同步数据的最佳方式是什么
- 不同/较旧的处理器运行c++代码的方式是否不同
- 从嵌套在std::映射中的std::列表中删除元素的最佳方式
- 如果条件为TRUE(最佳方式?),则在do while循环中后置增量
- 格式化浮点值:返回默认值
- 重载方法的方式会在使用临时调用时生成编译器错误
- 我需要一些帮助以有组织的方式格式化文件
- 以格式化的方式打开一个具有日期的文件,并获取该日期进行比较
- 如何格式化CPP方式
- 如何按照以下方式格式化双打
- 如何在c++中强制用户以格式化的方式输入
- Boost ptime:如何以浏览器在http请求的header内发送的方式格式化数据