c++ - 访问冲突错误 (while (info[x] != ' ' ))

标签 c++ loops cstring

#include <iostream>
#include <fstream>
#include <cstring>

using namespace std;

void main()
{
    char info[81];
    string names[5];
    double sales[5][5];
    int count = 0;
    int x = 0;
    ifstream file;
    file.open("sales.txt");

    while(!file.eof())
    {
        x = 0;
        file.getline(info, 80);
        while(info[x] != (char)39)
        {
            while(info[x] != ' ')
            {
                names[count] += info[x];
                x++;
            }
            x++;
            for(int y = 0; y < 4; y++)
            {
                sales[count][atoi(&info[x])] = (atoi(&info[x + 1]) * 10) + atoi(&info[x+2]) + (.01 *((atoi(&info[x+4])*10) + atoi(&info[x+5])));
                x += 7;
            }
            x++;
        }
        count++;
    }
}

运行时出现运行时错误,但我无法弄清楚具体原因。我不太熟悉我的编译器调试器,所以我在调试时遇到了麻烦。

最佳答案

我认为“x”超出了数组(信息)范围。在再次进入循环之前,您应该检查 x 是否小于 81。

例如:

while(x < 81 && info[x] != (char)39)
    {
        while(info[x] != ' ')
        {
            names[count] += info[x];
            x++;
        }
        x++;
        for(int y = 0; y < 4; y++)
        {
            sales[count][atoi(&info[x])] = (atoi(&info[x + 1]) * 10) + atoi(&info[x+2]) + (.01 *((atoi(&info[x+4])*10) + atoi(&info[x+5])));
            x += 7;
        }
        x++;
    }

无论如何,同样的情况也可能发生在循环内的行中。您假设您的输入将包含特定长度的字符串,如果没有发生,您将再次遇到该错误。


如果您尝试用空格分隔每一行,您可以考虑使用格式化输入(对于每一行):

        stringStream >> names[count];
        string theNextString;
        stringStream >> theNextString;
        // Process the theNextString, which is the string after the last space (and until the next one)

此外,这一行非常容易出错。我建议你把它分成更小的部分更容易理解(并且更少依赖于行的确切长度)。您甚至可以使用格式化输入来获取数字。

sales[count][atoi(&info[x])] = (atoi(&info[x + 1]) * 10) + atoi(&info[x+2]) + (.01 *((atoi(&info[x+4])*10) + atoi(&info[x+5])));

使用格式化输入,它看起来像

int firstNumber;
stringStream >> firstNumber;

请注意,以上内容仅在您的号码以空格分隔时有效。

关于c++ - 访问冲突错误 (while (info[x] != ' ' )),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13887844/

相关文章:

java - 在循环中生成随机数

c++ - getline() 省略了数组输出的第一个字母。

c++ - "no matching function for call to ‘async(std::launch, <unresolved overloaded function type>, std::string&)’“

c++ - 缺少 Visual Studio Express 2012 tracker.exe

Matlab:如何重新排序(重新组织)矩阵

r - 如何在 R 中从 REST API 检索数据时解决分页问题

C++14 模板函数转发引用由指针显式推导

C++ 将原始表转换为另一种表类型

c - 这个循环如何结束?

c++ - 将本地 CStringW 返回给调用者是否安全?