【问题标题】:How to read from input file (text file) and validate input as valid integer?如何从输入文件(文本文件)中读取并将输入验证为有效整数?
【发布时间】:2013-08-13 02:54:55
【问题描述】:

我正在编写一个程序,它需要读取一个文本文件并检查文本文件的第一行是否有 0 到 10 之间的数字。我想出了几个解决方案,但仍然存在问题:

我是如何阅读文件的:

const string FileName= argv[1];
ifstream fin(argv[1]);
if(!fin.good()){
    cout<<"File does not exist ->> No File for reading";
    exit(1);
}
getline(fin,tmp);
if(fin.eof()){
    cout<<"file is empty"<<endl;
}
stringstream ss(tmp);

首先我使用了atoi:

const int filenum = atoi(tmp.c_str());
    if(filenum<1 || filenum>10){
        cout<<"number of files is incorrect"<<endl;
        //exit(1);
    }

如果第一行是一个字符,把它改为零但是我想调用一个异常并终止程序。

然后我使用了isdigit,但我的条目是一个字符串,它不适用于字符串。 最后我使用了字符串中的每个字符,但仍然不起作用。

   stringstream ss(tmp);
   int i;
   ss>>i;
   if(isdigit(tmp[0])||isdigit(tmp[1])||tmp.length()<3)
   {}

【问题讨论】:

  • 你能说明你是如何从文件中读取的吗?在进行完整性检查时,您必须使用&amp;&amp; 操作而不是||。否则,您可以在提取操作后测试流的状态/标志。
  • 我已经编辑了,所以你可以看到我是如何阅读文件的
  • 好的。对于错误检查,您可以尝试 - if ( !(ss &gt;&gt; i) ) { std::cerr &lt;&lt; "Invalid number."; }
  • 我已经检查过了。问题是如果条目是 10D 它只读取 10 并在最后忽略 d?

标签: c++


【解决方案1】:
#include <iostream>
#include <fstream>
#include <cstdio>
#include <cstdlib>
using namespace std;

bool isValidNumber (string str)
{
  if (str.length() > 2 || str.length() == 0)
    return false;
  else if (str.length() == 2 && str != "10")
    return false;
  else if (str.length() == 1 && (str[0] < '0' || str[0] > '9'))
    return false;
  return true;
}

int main()
{
  ifstream fin(argv[1]);
  if(!fin.good())
  {
    cout<<"File does not exist ->> No File for reading";
    exit(1);
  }

  //To check file is empty http://stackoverflow.com/a/2390938/1903116
  if(fin.peek() == std::ifstream::traits_type::eof())
  {
    cout<<"file is empty"<<endl;
    exit(1);
  }
  string tmp;
  getline(fin,tmp);
  if (isValidNumber(tmp) == false)
  {
    cerr << "Invalid number : " + tmp << endl;
  }
  else
  {
    cout << "Valid Number : " + tmp << endl;
  }
}

【讨论】:

    【解决方案2】:

    我可能会阅读带有std::getline 的行,然后使用Boost lexical_cast 转换为int。除非输入字符串的整个可以转换为目标类型,否则它将抛出异常——正是你想要的。

    当然,你还需要检查转换后的结果是否在正确的范围内,如果超出范围也要抛出异常。

    【讨论】:

    • 我试过了,但#include 在我的头文件中不起作用并且无法识别!有什么想法吗?
    • @Bernard:您是否下载了 Boost 并配置了您的编译器(和 IDE,如果您正在使用的话)以找到您安装 Boost 的位置?
    • 哦,问题是我必须在无法安装任何东西的女妖服务器上运行我的程序!还有其他解决办法吗?
    • @Bernard:您只需要在编译时让标头可用。运行它不需要/不需要安装任何额外的东西。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-25
    相关资源
    最近更新 更多