使用文件提取操作符读取int或string

Read whether int or string using the file extraction operator

本文关键字:int string 读取 操作符 文件 提取      更新时间:2023-10-16

我正在从文件中读取,我正在使用提取操作符来获取第一个值。问题是我需要知道这个值是int还是string,这样我就可以把它放在合适的变量中。

我的问题是,我能不能把它放进int型如果失败,它会把它扔进字符串?或者事先检查它是整型还是字符串?

如果需要,我可以提供code/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

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

有几种方法可以解析字符串,包括(但不限于):
  • 使用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个字符查找

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

您应该能够将此示例转换为对文件中的所有"words"重复此过程。