Hi guys so I stored a file into an array of char pointer and allocated memory to it and right now Im trying to make the words lower case and I ran into a problem.
whenever my program gets into the loop I commented out it makes my program crash and im not sure why,considering one of my peers has the same exact line of code but for him it works. So why doesnt it work for me?
When I tried that, using the data file which I have, it failed when the word "transcontinental" was encountered - it is too large for the buffer char temp[16] so I increased the size to 50. (This is why in C++ the use of std::string is preferred instead of character arrays).
The rest of the code - the code should be checking whether or not the file access is successful - there's no point looping 23000 times if the file read failed after just three words or something. Make use of the actual count in the second loop.
#include <iostream>
#include <fstream>
#include <cstring>
#include <cctype>
#include <iomanip>
usingnamespace std;
constint SIZE = 23907;
int main()
{
char * wordFile[SIZE];
ifstream infile("unsorted_words.txt");
if (!infile)
{
cout<<"error opening file" << endl;
return 1;
}
int count = 0; // keep track of how many words have been read
char temp[50]; // don't know how long a word might be
while ( count < SIZE && infile >> temp)
{
// only enter loop body after successfully reading a word from the file
wordFile[count] = newchar[strlen(temp)+1];
strcpy(wordFile[count],temp);
cout << setw(8) << count << setw(20) << wordFile[count] << endl;
count++; // increment number of words read
}
cout << "\nNumber of words read from file = " << count << '\n';
for ( int i = 0; i < count; i++) // loop based on how mant words were actually read:
{
for (unsignedint j=0; j < strlen(wordFile[i]); j++)
{
wordFile[i][j] = tolower(wordFile[i][j]);
}
}
cout << "\nDone\n";
return 0;
}