Search code examples
c++segmentation-faultfstreamtype-conversionatoi

C++ segmentation fault related to atoi expression


I am a new to programming in C++ and I am trying to learn. Currently I am working on a program that reads from a file that has in proceeding lines a string followed by 3 integers.

Example: (This is first set of data, there are nine others in same format as below)

Linus too good
100
23
210

The strings are stored into a 1D array while the integers are stored into a 2D array.

So far I have this:

#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();

I isolated out, scores[r][c] = atoi(mystring.c_str()); and the program runs albeit it gives garbage values. Here is that output:

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

Thank you in advance for any help on this.


Solution

  • I think you might have to debug it first and then sort out the logic a bit.

    One bug is in the nested loops where you try to print out the results, and you used i twice in both outer and inner loops. (I don't think the inner loop for (i = 0; i < NUM_COL_SIZE; i++) is necessary.)

    Another bug is when you declare the 2D array scores. Try double scores[10][3];

    I have tried your code w/ these two fixes and it worked.

    Welcome to C++ and fun debugging!