atoi(str); not working

Hello am a beginner and am working on this assignment and this line does not work please help its urgent.
the line that does not work is atoi(str);


int main() {
int aId[11], aSum[11] = { 0 }, aCount[11] = { 0 };
double aAvg[11];
int n = 10;
string fileName = "inputProduct.txt";
populateArray(100, aId, aSum, aCount, fileName);
calculateProduct(n, aId, aSum, aCount, aAvg);
showAllRatings(n, aId, aAvg, aCount);

showBestWorstProducts(n, aId, aAvg);
searchAndShowSelectedProduct(n, aId, aAvg, aCount);
return 0;
}
//________________________
void populateArray(int n, int aId[], int aSum[], int aCount[], string fileName) {
ifstream file;
file.open("inputProduct.txt");
string str;

for (int i = 0; i < n; i++)
{
file >> str;
int pid = atoi(str);
file >> str;
int rating = atoi(str);
aId[pid] = pid;
aSum[pid] += rating;
aCount[pid]++;

}
Last edited on
First, code tags and indentation make posted code easier to read and comment. See https://www.cplusplus.com/articles/jEywvCM9/
Your code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
int main() {
  int aId[11], aSum[11] = { 0 }, aCount[11] = { 0 };
  double aAvg[11];
  int n = 10;
  string fileName = "inputProduct.txt";
  populateArray(100, aId, aSum, aCount, fileName);
  calculateProduct(n, aId, aSum, aCount, aAvg);
  showAllRatings(n, aId, aAvg, aCount);

  showBestWorstProducts(n, aId, aAvg);
  searchAndShowSelectedProduct(n, aId, aAvg, aCount);
  return 0;
}

void populateArray(int n, int aId[], int aSum[], int aCount[], string fileName) {
  ifstream file;
  file.open("inputProduct.txt");
  string str;

  for (int i = 0; i < n; i++)
  {
    file >> str;
    int pid = atoi(str);
    file >> str;
    int rating = atoi(str);
    aId[pid] = pid;
    aSum[pid] += rating;
    aCount[pid]++;
  }


Second, that is nowhere close to complete program that one could compile; with errors only in the atoi().

This focuses on them:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
// my first program in C++
#include <string>
#include <fstream>
using std::string;
using std::ifstream;

void populateArray(int n, int aId[], int aSum[], int aCount[], string fileName) {
  ifstream file;
  file.open("inputProduct.txt");
  string str;

  for (int i = 0; i < n; i++)
  {
    file >> str;
    int pid = atoi(str);
    file >> str;
    int rating = atoi(str);
    aId[pid] = pid;
    aSum[pid] += rating;
    aCount[pid]++;
  }
}

 In function 'void populateArray(int, int*, int*, int*, std::string)':
15:23: error: cannot convert 'std::string {aka std::basic_string<char>}' to 'const char*' for argument '1' to 'int atoi(const char*)'
17:26: error: cannot convert 'std::string {aka std::basic_string<char>}' to 'const char*' for argument '1' to 'int atoi(const char*)'

The atoi() expects a pointer (to array of char), not a std::string. See http://www.cplusplus.com/reference/cstdlib/atoi/

There is std::stoi() that would use std::string. See http://www.cplusplus.com/reference/string/stoi/

However, why read strings at all? You can read integers directly:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
void populateArray(int n, int aId[], int aSum[], int aCount[], string fileName) {
  ifstream file;
  file.open( fileName );

  int pid {};
  int rating {};
  while ( n && file >> pid >> rating )
  {
    --n;
    aId[pid] = pid;
    aSum[pid] += rating;
    aCount[pid]++;
  }
}

Last edited on
atoi / atof are for c-style strings. you can call the c-string (c_str()) on a string to force it to work but stoi stod stof family are what you should use here for now, they work on c++ string objects. Later you will discover the helper classes for strings (stringstream) that can do this as well.

also use code tags please. you did great saying what the problem was, but its a lot easier with syntax coloring etc on the code. Also you need prototypes above main if you put main above the functions.
void populateArray(int n, int aId[], int aSum[], int aCount[], string fileName) ; //prototype
int main()

you can also read directly into the right type of variable.
file >> integer_variable will convert the text in the file to an integer for you. You don't have to read as text if you trust the source; the biggest reason to read as text and convert is if you do input validation (to make sure its really a number, for example).
Last edited on
1.
PLEASE learn to use code tags, they make reading and commenting on source code MUCH easier.

http://www.cplusplus.com/articles/jEywvCM9/
http://www.cplusplus.com/articles/z13hAqkS/

HINT: you can edit your post and add code tags.

Some formatting & indentation would not hurt either


2. Without showing what headers you are using we need to use a crystal ball to divine what the problem might be.

If you are using atoi from <cstdlib> the function doesn't work with C++ strings. Only C style (null terminated char array) strings.

If you aren't including <string> your compiler might be substituting the C library function for the C++ function.
sorry am getting a Exception thrown: read access violation.
aSum was 0x35142C3A. error
please help and many thanks.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
#include<iostream>
#include<fstream>
#include<time.h>
using namespace std;
//________________________
void populateArray(int n, int aId[], int aSum[], int aCount[], string fileName);
void calculateProduct(int n, int aId[], int aSum[], int aCount[], double aAvg[]);
void showAllRatings(int n, int aId[], double aAvg[], int aCount[]);
void showBestWorstProducts(int n, int aId[], double aAvg[]);
void searchAndShowSelectedProduct(int n, int aId[], double aAvg[], int aCount[]);
//___main()____________________
int main() {
    int aId[11], aSum[11] = { 0 }, aCount[11] = { 0 };
    double aAvg[11];
    int n = 10;
    string fileName = "c:\temp\rateMyProduct.txt";
    populateArray(100, aId, aSum, aCount, fileName);
    calculateProduct(n, aId, aSum, aCount, aAvg);
    showAllRatings(n, aId, aAvg, aCount);

    showBestWorstProducts(n, aId, aAvg);
    searchAndShowSelectedProduct(n, aId, aAvg, aCount);
    return 0;
}
//________________________
void populateArray(int n, int aId[], int aSum[], int aCount[], string fileName) {
    ifstream file;
    file.open(fileName);

    int pid{};
    int rating{};
    while (n && file >> pid >> rating)
    {
        --n;
        aId[pid] = pid;
        aSum[pid] += rating;
        aCount[pid]++;
    }
}
//________________________
void calculateProduct(int n, int aId[], int aSum[], int aCount[], double aAvg[]) {
    for (int i = 1; i <= n; i++) {
        int pid = aId[i];
        aAvg[pid] = (float)aSum[pid] / aCount[pid];
    }
}
//________________________
void showAllRatings(int n, int aId[], double aAvg[], int aCount[]) {
    cout << "Dataset - Product Rating (Five Stars)" << endl;
    for (int i = 1; i <= n; i++) {
        int pid = aId[i];
        cout << "Prod. " << pid << "\t\t" << "Stars: " << aAvg[pid] << "\t" << "Review: " << aCount[pid] << endl;
    }
}
//________________________
void showBestWorstProducts(int n, int aId[], double aAvg[]) {
    double bestAvg = aAvg[1], worstAvg = aAvg[1];
    int bestPid = aId[1], worstPid = aId[1];
    for (int i = 2; i <= n; i++) {
        int pid = aId[i];
        if (aAvg[pid] > bestAvg) {
            bestAvg = aAvg[pid];
            bestPid = pid;
        }
        if (aAvg[pid] < worstAvg) {
            worstAvg = aAvg[pid];
            worstPid = pid;
        }
    }
    cout << "---------------------------------------------" << endl;
    cout << "Best Product(s): Product: " << bestPid << "(" << bestAvg << " stars)," << endl;
    cout << "Worst Product(s): Product: " << worstPid << "(" << worstAvg << " stars)," << endl;
    cout << "---------------------------------------------" << endl;
}
//________________________
void searchAndShowSelectedProduct(int n, int aId[], double aAvg[], int aCount[]) {
    cout << "Retriev product by ID" << endl;
    int pid;
    while (true) {
        bool flag = true;
        cout << "Enter product ID[0-" << n << "]: ";
        cin >> pid;
        if (pid == 0) {
            cout << "All done!" << endl;
            return;
        }
        for (int i = 1; i <= n; i++) {
            if (pid == aId[i]) {
                cout << "Product " << pid << " (" << aAvg[pid] << " Stars, " << aCount[pid] << " Reviews)" << endl;
                flag = false;
            }
        }
        if (flag)
            cout << "Sorry - Product not found - Try again" << endl;
    }
}
Last edited on
I repeat:
PLEASE learn to use code tags, they make reading and commenting on source code MUCH easier.

http://www.cplusplus.com/articles/jEywvCM9/
http://www.cplusplus.com/articles/z13hAqkS/

HINT: you can edit your post and add code tags.

Some formatting & indentation would not hurt either

Make your code readable before we continue.

And post the EXACT error code if any you are receiving, not what you think it is.

WHERE is #include <string> ? You want to use C++ string you need to include the header.

Oh, BTW, since you are retrieving data from a file posting a SAMPLE of the file contents would be helpful. Without something for us to test hard to tell if things are really working.

Pro tip: When working with files ALWAYS check if the file was actually opened. Trying to read from a file that wasn't opened doesn't work. Same for trying to write to a file that couldn't be opened.
@tron22,
Your array access is going out of bounds.

e.g.
1
2
for (int i = 1; i <= n; i++) {
int pid = aId[i];


In C++ (and related languages) and python your array elements are indexed from 0; thus
0, 1, ..., n-1
So aId[i] will not cut it when i=n.

In matlab and Fortran the array indices go from 1 to n, but not here.


But please do as the others have said:
- USE CODE TAGS
- POST YOUR INPUT FILES
Otherwise nobody can read or run your program.

sorry for that i edited it and my input files .txt file that has numbers in two columns which are:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
2 4
1 5
5 4
9 3
5 1
6 3
2 3
3 3
7 2
5 3
4 4
2 3
6 4
2 5
3 3
10 2
4 3
4 5
2 3
9 3
5 3
8 4
4 3
9 2
6 2
9 2
1 3
5 4
7 1
1 5
1 1
7 2
4 5
4 5
7 1
7 2
2 5
10 3
8 5
3 5
2 5
10 5
1 3
7 4
7 2
6 5
1 5
8 5
3 2
1 2
7 1
8 2
2 4
1 2
5 2
1 3
2 4
8 4
4 2
10 5
9 3
7 2
1 4
9 1
2 4
1 5
5 3
9 4
6 3
1 2
7 5
1 2
2 5
9 5
2 5
10 5
1 4
8 4
4 5
8 3
8 5
10 3
2 2
10 3
4 5
5 5
10 4
6 5
4 4
4 5
9 4
1 2
9 2
10 5
8 4
9 3
9 5
1 3
9 2
6 5
Last edited on
M'ok, Read Access Violation.

I'd bet your file isn't being opened. As I said ALWAYS check the file you tried to open is actually open and ready to be used.

https://stackoverflow.com/questions/21258277/detect-if-file-is-open-in-c/21258642#21258642

You clearly are using Windows. Windows gets rather anal about file paths. Instead of single \ separators you should use double \\.

IOWs: string fileName = "c:\\temp\\rateMyProduct.txt";

Can you confirm the file does actually exist at that location?

A sample of the file contents posted here would be VERY helpful.
yes it does exist but i don't know why it isn't opening
I also posted the file contents above
Last edited on
> yes it does exist but i don't know why it isn't opening
Well you could print the reason why it didn't open.
The common reasons being
- file not found
- permission denied.
https://stackoverflow.com/questions/17337602/how-to-get-error-message-when-ifstream-open-fails

Also, it helps to turn OFF the "hide extensions of known file types" in explorer.
You might be looking at rateMyProduct.txt but it's really called rateMyProduct.txt.txt
thanks guys i got it
Topic archived. No new replies allowed.