I would like to read a text file and input its contents into an array. Then I would like to show the contents of the array in the command line.
My idea is to open the file using:
inFile.open("pigData.txt")
And then to get the contents of the file using:
inFile >> myarray [size]
And then show the contents using a for loop.
My problem is that the file I am trying to read contain words and I don’t know how to get a whole word as an element in the array. Also, let’s say that the words are divided by spaces, thus:
hello goodbye
Could be found on the file. I would like to read the whole line “hello goodbye” into an element of a parallel array. How can I do that?
For context, you could have provided a link to your previous question, about storing two lists of words in different languages. There I provided an example of reading the contents of a text file into an array:
You can’t have one parallel array. For something to be parallel, there must be at least two. For parallel arrays of words, you could use a declarations like this:
Then you have two options for filling the arrays from the file:
Read an entire line, and the split the line into two words based on where the first space is:
Read one word at a time, and assume that each line has exactly two words on it. The
>>operator will read a word at a time automatically. (If each line doesn’t have exactly two words, then you’ll have problems. Try it out to see how things go wrong. Really. Getting experience with a bug when you know what the cause is will help you in the future when you don’t know what the cause is.)Now, if you really one one array with two elements, then you need to define another data structure because an array can only have one “thing” in each element. Define something that can hold two strings at once:
Then you’ll have just one array:
You can fill it like this:
Notice how the code indexes into the
wordsarray to find the nextword_pairobject, and then it uses the.operator to get to thepiglatinorenglishfield as necessary.