简体   繁体   中英

How to copy words from .txt file into an array. Then print each word on a separate line

The goal is to read a set of strings from a file called "words.txt" and save each word into the array strings. However I am have trouble saving and printing the words to the console. I think the problem is within my GetStrings function but I can't figure out why. Nothing prints out to the console when the PrintStrings function is called. Which makes me think that either nothing is being saved into the array or the print function is not correct.

int main ()
{
    int count = 0;
    string strings [MAXSTRINGS];
    GetStrings(strings);
    // cout << strings[1];
    PrintStrings(strings, count);
    return 0;
}

int GetStrings (string S [])
{
    ifstream input ("words.txt");
    int count = 0;
    while (input >> S[count])
    {
        count++;
    }
    input.close ();
    return 0;
}

void PrintStrings (string S [], int C)
{
    int w = 0;
    while (w < C)
    {
        cout << S[w] << endl;
        w++;
    }
}

The problem is local variables. Variables declared inside functions cannot be used by other functions:

int GetStrings (string S [])
{
    ifstream input ("words.txt");
/* --> */    int count = 0;

Here's where it's used:

PrintStrings(strings, count);

The variable count inside the function GetStrings is a different variable than the one in main .

If you want a function to modify an external (to the function) variable, pass it by reference:

  int GetStrings (string S [], int& count)

I recommend exchanging the array for std::vector . The std::vector maintains its count and you can access it by using std::vector::size() .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM