【问题标题】:stoi function gives error: std::invalid_argument at memory location 0x0035E8D8. c++stoi 函数给出错误:内存位置 0x0035E8D8 处的 std::invalid_argument。 C++
【发布时间】:2015-08-10 20:37:35
【问题描述】:

程序运行良好,直到它到达 stoi 函数,然后程序中断并给我这个错误“Microsoft C++ exception: std::invalid_argument at memory location 0x0030EE7C”。我看过关于使用 stoi 的教程,但我不确定我做错了什么。平面文件如下所示:

Organic
7
description
light
4
description
menthol
5
description.

每个单词或数字换行。

struct ProdDescriptor
{
    string name;
    string price;
    string descript;

};
void getProds() // reads products off of the flat file
{
    int array = 3;
    ProdDescriptor x[3];
    ifstream ItemRead(FlatFileName); // object of the flat file
    string temp;

    if (ItemRead.is_open()) // opens flat file and reads
    {
        for (int i = 0; i < array; i++)
        {
            ProdSpecPrice[i] = 0; // initialize 

            getline(ItemRead, x[i].name);
            getline(ItemRead, x[i].price);
            getline(ItemRead, x[i].descript);

            temp = x[i].price;
            ProdSpecPrice[i] = stoi(temp);
            ProdSpecName[i] = x[i].name;
            ProdSpecDescription[i] = x[i].descript;
        }

【问题讨论】:

  • 拨打stoi()temp的实际内容是什么。请您在此处展示您的调试观察结果!
  • 是的,您需要检查temp 的值。 stoi 将抛出 invalid_argument if no conversion could be performedgetline 是否删除 \n?我想是的.. 但是由于您使用的是 Windows(我在这里做假设),我不确定getline 是否删除了\r
  • @πάντα ῥεῖ 数字 7。
  • @RIDDLEisVoltron 你在 Windows 上吗?您的文件是否使用 CRLF(或者您不确定)? temp (temp.length()) 的大小是否等于 2 但应该是 1 ?如果您对这些问题的回答正确,请查看this thread
  • 是的,Windows 7、64 位、Visual Studios 2013。我正在阅读 .txt 文件。我没有给 temp 指定长度,有必要吗?

标签: c++


【解决方案1】:

reference documentation 开始,std::stoi() 肯定会抛出这些异常:

例外情况

std::invalid_argument 如果无法执行转换 std::out_of_range 如果转换后的值将超出结果类型的范围,或者基础函数(std::strtolstd::strtoll)将 errno 设置为 ERANGE

因此,此例外取决于您的实际输入,而您目前没有从您的问题中透露(很遗憾)。

【讨论】:

  • 输入应该是数字 7,我开始认为错误可能与 .txt 格式有关。我应该查看哪些内容以确保平面文件正确读取?
  • 我收回了。我手动分配 temp = 7;它仍然坏了。
  • @RIDDLEisVoltron:不幸的是,这个任务并没有达到你的预期。试试temp = 55;,看看能不能转化。
  • @RIDDLEisVoltron: std::string 有一个赋值运算符,它接受 char,并将字符串设置为将单个 char 作为其值。 55 是字符“7”的 ASCII 码。所以temp = 55; 等价于temp = "7";——当您执行temp = 7; 时,您将一些非打印字符(钟形字符)分配给temp
  • @AlanStokes 当然我的意思是不披露,感谢指出错字!
猜你喜欢
  • 2017-08-03
  • 1970-01-01
  • 2014-03-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多