Aray of strings

closed account (EvCSLyTq)
I don't know why this is working. It seems good to me. Please help.
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
#include <iostream>
#include <string>
#include <fstream>

using namespace std;

int main(){
    
    int items = 355600;
    string inventory[items];
    int i = 0;
    ifstream File;
    File.open ("textfile.txt");
    string word;
    
    if (File.is_open())
    {
    while (!File.eof())
    {
    getline(File,word);
    inventory[i] = word;
    i++;
    }
}
    cout << word[20] << endl;
    system("pause");
    return 0;
}
What seems to be the problem?

What is your program outputting?

What do you expect it to output?

What is the contents of your input file?

Are you sure word has 20 characters?


Note: this program shouldn't even compile. Array sizes must be compile time constants in C++.

When allocating an array the size needs to be constant when allocated on the stack. You can allocate it on the heap to use a non constant array size like so:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
int items = 355600;
    string* inventory = new string[items];
    int i = 0;
    ifstream File;
    File.open ("textfile.txt");
    string word;

    if (File.is_open())
    {
        while (!File.eof())
        {
            getline(File,word);
            inventory[i] = word;
            i++;
        }
    }
    cout << word[20] << endl;
    system("pause");

    delete [] inventory;


Just make sure you delete the array (you should always delete anything allocated using new).
closed account (EvCSLyTq)
I have found the solution:

I changed:
cout << word[20] << endl;

to:
cout << inventory[20] << endl;

I wanted the program to get the strings from text file to RAM (to aray of strings) and print the 20th word in the array.

What did you mean by that?

Note: this program shouldn't even compile. Array sizes must be compile time constants in C++.
Last edited on
What did you mean by that?

Note: this program shouldn't even compile. Array sizes must be compile time constants in C++.

Exactly what I said, your program shouldn't compile. You are using a non-constant when creating your array, that is not allowed in C++. In C++ array sizes must be compile time constants, your size is not a constant.
Topic archived. No new replies allowed.