使用文件提取运算符读取int或string

时间:2015-09-26 01:40:58

标签: c++

我正在读取文件,我正在使用提取运算符来获取第一个值。问题是我需要知道值是int还是字符串,所以我可以把它放在适当的变量中。

所以我的问题是我可以尝试将它放在一个int中,如果它失败了它会把它扔进一个字符串中吗?或事先检查一下它是一个int还是一个字符串?

如果需要,我可以提供代码/ psudocode。

文件示例:

   3 rows  3 columns all @ go
        5 columns 6  rows go
        5     rows        triangular        go
alphabetical   3 rows    3       columns go
 all !  4 rows  4 columns outer     go
 alphabetical      triangular       outer      5 rows   go

2 个答案:

答案 0 :(得分:2)

有很多方法可以做到这一点,一种是简单地将其作为字符串读取,并尝试在自己的代码中将其解析为整数。如果解析成功,那么你有一个整数,否则你有一个字符串。

有几种方法可以解析字符串,包括(但不限于):

  • 使用std::istringstream>>运算符,并检查流标志
  • std::stoi
  • 以编程方式检查所有字符是否为数字,使用普通的十进制算术进行转换。

使用std::stoi的简单示例:

std::string input;
if (std::getline(std::cin, input))
{
    try
    {
        std::size_t pos;
        int n = std::stoi(input, &pos);

        // Input begins with a number, but may contain other data as well
        if (pos < input.length())
        {
            // Not all input was a number, contains some non-digit
            // characters as position `pos`
        }
        else
        {
            // Input was a number
        }
    }
    catch (std::invalid_argument&)
    {
        // Input is not a number, treat it as a string
    }
    catch (std::out_of_range&)
    {
        // Input is a number, but it's to big and overflows
    }
}

如果您不想使用例外,则可以使用旧的C函数std::strtol

std::string input;
if (std::getline(std::cin, input))
{
    char* end = nullptr;
    long n = std::strtol(input.c_str(), &end, 10);

    if (n == LONG_MAX && errno == ERANGE)
    {
        // Input contains a number, but it's to big and owerflows
    }
    else if (end == input.c_str())
    {
        // Input not a number, treat as string
    }
    else if (end == input.c_str() + input.length())
    {
        // The input is a number
    }
    else
    {
        // Input begins with a number, but also contains some
        // non-number characters
    }
}

答案 1 :(得分:1)

执行此操作的标准方法是使用1个字符预测

int nextInt()
{
   std::stringstream s;
   while (true) 
   {
       int c = getch();
       if (c == EOF) break;
       putch(c); // remove if you don't want echo

       if isDigit(c) 
          s << (char)c;
       else if (s.str().length() > 0)
           break;        
   }

   int value;
   s >> value;
   return value;
}

您应该能够转换此示例,以便为文件中的所有“单词”重复此过程。