与atoi表达式相关的C ++分段错误

时间:2016-04-09 00:33:06

标签: c++ segmentation-fault fstream type-conversion atoi

我是C ++编程的新手,我正在努力学习。目前我正在开发一个程序,该程序从一个文件中读取,该文件在前面的行中有一个字符串后跟3个整数。

示例:(这是第一组数据,其他九种格式与下面相同)

Linus too good
100
23
210

字符串存储在1D数组中,而整数存储在2D数组中。

到目前为止,我有这个:

#include <stdlib.h>
#include <iostream>
#include <fstream>
#include <string>

void FileToArray(); 

using namespace std;

int main() 
{
    FileToArray();

    return 0;
}

void FileToArray()
{
    ifstream inFile;

    inFile.open("bowlers2.txt");

    const int STRING_ARRAY_SIZE = 10;
    const int NUM_ROW_SIZE = 3;
    const int NUM_COL_SIZE = 10;

    double scores[NUM_ROW_SIZE][NUM_COL_SIZE];
    string names[STRING_ARRAY_SIZE];
    string mystring;

    for(int r = 0; r < 10; r++)
    {
        getline(inFile, names[r]);

        for(int c = 0; c < 3; c++)
        {
            getline(inFile, mystring);
            scores[r][c] = atoi(mystring.c_str());
        }
    }
    cout << "The names are:\n";
    for (int i = 0; i < STRING_ARRAY_SIZE; i++)
    {
        cout << names[i] << "\n";
        for (i = 0; i < NUM_COL_SIZE; i++)
        {
            for (int j = 0; j < NUM_ROW_SIZE; j++)
            {
            cout << scores[i][j] << "\n";
            }
        }
    }
}
inFile.close();

我孤立了,得分[r] [c] = atoi(mystring.c_str());程序运行虽然它给出了垃圾值。 这是输出:

The names are:
Linus too good
0
2.96439e-323
6.63467e-315
6.95306e-310
6.94939e-310
1.4822e-323
2.52023e-320
6.94939e-310
6.94939e-310
6.95306e-310
6.91692e-323
7.6287e+228
6.59695e-310
6.94939e-310
6.95306e-310
6.95306e-310
7.41098e-323
3.44197e+175
1.69599e+161
5.83684e-310
6.95306e-310
6.94939e-310
0
6.94939e-310
0
0
0
0
1.02437e-316
4.04739e-320

提前感谢您提供任何帮助。

2 个答案:

答案 0 :(得分:0)

您声明的数组的最大行数= 3且列数= 10,但您正在反向访问。所以交换

scores[r][c] = atoi(mystring.c_str());

scores[c][r] = atoi(mystring.c_str());

答案 1 :(得分:0)

我认为您可能必须先调试它,然后稍微整理一下逻辑。

嵌套循环中有一个错误,您尝试打印出结果,并且在外循环和内循环中都使用了i两次。 (我不认为内循环for (i = 0; i < NUM_COL_SIZE; i++)是必要的。)

另一个错误是当您声明2D数组scores时。试试double scores[10][3];

我已尝试过这两个修复程序的代码,但它确实有效。

欢迎使用C ++并进行有趣的调试!