如何在c++中强制用户以格式化的方式输入

How to force the user to input in a formatted way in c++

本文关键字:格式化 方式 输入 用户 c++      更新时间:2023-10-16

我应该强制用户输入一个数字,然后输入一个空格,然后输入字符串,如果格式错误,我应该终止程序。当我使用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
}