【发布时间】:2018-01-27 21:23:20
【问题描述】:
很抱歉我是 C 新手。我之前学过一点 C++,可能会混淆 C 和 C++。但我正在尝试编写一个 C 程序。我唯一可以在 C++ 中应用的是向量。这对我来说是一个练习。请告诉我我犯的任何错误。非常感谢。
我正在开发一个程序来计算文本文件中单词的频率,并输出文本文件中的单词列表和相应的频率。程序中止并显示错误消息:
C2036: 'char(*)[]: unknown size'.
它指向矢量文件中的以下几行:
1475: _Move_unchecked(_VIPTR(_Where) + 1, this->_Mylast(), _VIPTR(_Where));
1476: _Destroy(this->_Mylast() - 1, this->_Mylast());
1478: --this->_Mylast();
我能理解的是在
line 1474: _DEBUG_ERROR("vector erase iterator outside range");
但我不知道这个问题。我确实搜索了类似的问题,但我发现解决方案是针对海报代码的。请帮忙。谢谢。
#include <stdio.h>
#include <stdlib.h>
#include <vector>
#include <ctype.h>
void main(int argc, char *argv[])
{
char *str;
int wordLocation, insertLocation, wordLength;
wordLocation = insertLocation = wordLength = 0;
char *wordCheck;
std::vector<char[]> word;
std::vector<int> frequency;
std::vector<char[]> tempWord;
int tempFreq;
FILE *file;
file = fopen(argv[1], "r");
if (file)
{
//Read file test
/*while (fscanf(file, "%s", str)!= EOF)
{
printf("s%\n",str);
}
*/
while (fscanf(file, "%s",word.end()) != EOF)
{
wordCheck = word[wordLocation];
wordLength = strlen(wordCheck);
for (int i = 0; i < wordLength; i++, wordCheck++)
{
// Check and remove punctuation
if (ispunct(*wordCheck))
{
*wordCheck = ' ';
}
// Check uppercase and transform to lowercase
if (*wordCheck >= 'A' && *wordCheck <= 'Z')
{
*wordCheck = putchar(tolower(*wordCheck));
}
}
// Start to compare word in vector word
if (int(word.size()) == 1)
{
//only contain 1 input
frequency[wordLocation] = 1;
}
else
{
for (int i = 0; i <= wordLocation; i++)
{
// Look for the same word
if (word[i] == word[wordLocation])
{
frequency[i]++;
word.erase(word.end()-1);
break;
}
// Add new word at the end
else if (i == wordLocation && word[i] != word[wordLocation])
{
frequency[wordLocation] = 1;
}
}
}
wordLocation++;
}
// Word Sorting
for (int i = 0; i <= wordLocation; i++)
{
for (int k = 0; k <= wordLocation - 1; k++)
{
if (frequency[i] < frequency[i + 1])
{
//Swap element
tempWord.insert(tempWord.begin(),word[i]);
tempFreq = frequency[i];
word.erase(word.begin());
frequency.erase(frequency.begin());
word.insert(word.begin() + i + 1, tempWord.front());
frequency.insert(frequency.begin() + i + 1,tempFreq);
tempWord.pop_back();
}
}
}
// After sorting, write into the file
fclose(file);
remove("output.txt");
file = fopen("output.txt", "a");
file = fopen("output.txt", "w");
for (int i = 0; i <= wordLocation; i++)
{
fprintf(file, "%s %d \n", word[i], frequency[i]);
}
printf("Create output.txt successed.");
}
else
{
printf("Read file fail. Please check the input path.\n");
}
}
【问题讨论】:
-
提炼你的程序,直到它最小但仍然崩溃。
-
这不是 C 而是 C++,不同的语言。
-
Jonathan Leffler 注意到 Stack Overflow 主动 建议同时标记两种语言。 He posted to meta about it.
-
如果你想写一个 C 程序,你的第一个错误是你写了一个 C++ 程序。那么,您可能应该删除 C++ 标记。
-
最好使用C编译器来编写“C程序”。
标签: c++ c arrays pointers vector