This code compiles, but does not display anything. I am reading the whole file so that I can get character count for any word in the list. I am trying to see if that extra character at the end of each word in dictionary.txt is really a space, a newline, or what it is. Why is it not displaying anything? My laptop only has 4GB of RAM, so could it be a memory issue?
//dictionary.txt is found here: https://dev.intentionrepeater.com/cpp/dictionary.txt
#include <stdio.h>
#include <string>
#include <iostream>
#include <fstream>
#define SIZE_OF_WORD_LIST 49528
using namespace std;
int main() {
std::string word_list[SIZE_OF_WORD_LIST-1];
int i;
ifstream file("dictionary.txt");
try
{
if (file.is_open()) {
for (i = 0; i < SIZE_OF_WORD_LIST; ++i) {
file >> word_list[i];
}
}
}
catch (int e)
{
cout << "Error opening file: " << e << endl;
exit(0);
}
cout << "Number of characters in first word: " << std::to_string(word_list[0].length()) << endl;
return 0;
}
In C++ you have to specify the number of elements, not the maximum index, when you declare arrays. You allocated only SIZE_OF_WORD_LIST-1
elements, but have it read upto SIZE_OF_WORD_LIST
words.
It seems a Segmentation Fault invoked by acessing the nonexistent element word_list[SIZE_OF_WORD_LIST-1]
is preventing it from printing.
To avoid this, allocate enough elements. In other words, use
std::string word_list[SIZE_OF_WORD_LIST];
instead of
std::string word_list[SIZE_OF_WORD_LIST-1];
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.