如何从输入文件(文本文件)读取并将输入验证为有效整数? [英] How to read from input file (text file) and validate input as valid integer?

查看:74
本文介绍了如何从输入文件(文本文件)读取并将输入验证为有效整数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm writing a program which needs to read a text file and check first line of the text file for a number between 0 to 10. I have come up with a couple of solutions but there is still a problem:

我如何读取文件:

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);
    }

如果第一行是字符,请将其更改为零,但我想

If the first line is a character, change it to zero But I want to call an exception and terminate the program.

然后我使用了 isdigit ,但是我输入的是字符串,但没有使用字符串。
最后,我使用了字符串中的每个字符,但仍然无法使用。

Then I used isdigit but my entry is a string and it does not work with string. Finally I used each character in string but still does not work.

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


推荐答案

#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;
  }
}

这篇关于如何从输入文件(文本文件)读取并将输入验证为有效整数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆