[英]Is this the right way to get the character count for the first word (or any word) in a dictionary file in C++?
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.我试图查看 dictionary.txt 中每个单词末尾的额外字符是否真的是空格、换行符或它是什么。 Why is it not displaying anything?为什么它不显示任何东西? My laptop only has 4GB of RAM, so could it be a memory issue?我的笔记本电脑只有 4GB 内存,这会不会是 memory 问题?
//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.在 C++ 中,当您声明 arrays 时,您必须指定元素的数量,而不是最大索引。您只分配了SIZE_OF_WORD_LIST-1
元素,但让它读取SIZE_OF_WORD_LIST
单词。
It seems a Segmentation Fault invoked by acessing the nonexistent element word_list[SIZE_OF_WORD_LIST-1]
is preventing it from printing.似乎通过访问不存在的元素word_list[SIZE_OF_WORD_LIST-1]
调用的分段错误正在阻止它打印。
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];
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.