【问题标题】:C++ check for specific number of inputC++ 检查特定数量的输入
【发布时间】:2014-11-26 07:30:21
【问题描述】:

我有一个提示用户输入的功能。如果他们输入的字数超过了我想要的字数(3),那么应该打印一个错误。我该如何处理?我发现了如何检查输入是否为 3。

struct Info
{
  std::string cmd;
  std::string name;
  std::string location;
}

Info* get_string()
{
  std::string raw_input;
  std::getline(std::cin, raw_input);
  std::istringstream input(raw_input);

  std::string cmd;
  std::string name;
  std::string location;

  input>>cmd;
  input>>name;
  input>>location;

  Info* inputs = new Info{cmd, name, location};

  return inputs;
}

我的函数自动获取 3 个字符串并将它们存储在我的结构中,稍后我会检查结构的任何部分是否为空(例如:“Run”“Joe”“”),但如果它们输入4个字符串?谢谢

【问题讨论】:

  • 第四个字符串是否应该被忽略是有争议的,这里没有问。我不明白反对票。问题提示:尝试读取第四个字符串并期望它失败(例如为空)!
  • 当我刚开始编程并且正在寻找更好的编码方式时,我想人们会认为这是一个愚蠢的问题。无论如何,我正在考虑看第四个,但在我的情况下我该怎么做呢?我是否必须在我的结构中创建另一个元素来表示第四个字符串?
  • 不,您只需要在 get_string 函数中添加第四个本地 std::string 变量:std::string remainder; input << remainder; if (!remainder.empty()) { /* user has given a forth word */ }。将您甚至不感兴趣的数据复制到 Info 结构中是没有意义的。

标签: c++ string input


【解决方案1】:

您可以将输入字符串拆分为带有空格分隔符的单词,然后检查单词的数量。您可以使用下面的功能来拆分您的输入。在此之后,您可以检查向量的大小。

#include <vector>
#include <string>
#include <iostream>
#include <sstream>
using namespace std;

vector<std::string> split(const string &s, char delim) {
    stringstream ss(s);
    string item;
    vector<string> res;
    while (getline(ss, item, delim)) {
        if(item.length()==0)continue;
        res.push_back(item);
    }
    return res;
}
int _tmain(int argc, _TCHAR* argv[])
{

    string theString;
    cin>>theString;
    vector<string> res=split(theString, ' ');
    if(res.size()>3)
    {
        //show error
    }
    return 0;
}

【讨论】:

  • 这有点过分了。除了通过创建多个向量、另一个流和一个字符串来产生高开销之外,您只需要查看最后一个单词。如果用空格分隔,&gt;&gt; 运算符是获取所需内容的最佳方式,所以如果您可以只扫描最后一个字符串,为什么还要扫描整个字符串。
  • 你可以使用 strtok 来分割字符串。这会更快。在我看来,它仍然比使用 >> n 次更好。
【解决方案2】:

这个问题和费迪南德的想法是,为了测试第四个字符串是否存在,你必须“询问”它。如果存在,您可能会出错,但如果不存在,则它会坐在那里等待输入,用户想知道出了什么问题。

因此,我将稍微修改您的代码。这是相当直接的。如果用户在最后一个“单词”中输入了一个空格,那么您就知道有问题并且可以按照您的意愿处理。

// Replace input >> location; with the below
// Get until the line break, including spaces
getline(input, location);

// Check if there is a space (I.e. 2+ words)
if(location.find(" ") != string::npos){
    // If so, fail
}

学习资源:

http://www.cplusplus.com/reference/string/string/find/
http://www.cplusplus.com/reference/string/string/getline/

【讨论】:

  • 您遗漏了一个细节:在问题的示例中,用户输入被读入变量std::istringstream input,然后该变量的内容被拆分。尝试读取第四个字符串不会阻塞程序并等待用户输入。
猜你喜欢
  • 2015-04-03
  • 2015-04-04
  • 2019-12-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-02-06
相关资源
最近更新 更多