【发布时间】:2015-02-08 03:10:58
【问题描述】:
这里是说明:
编写一个程序,一次读入一个文本文件。首次遇到单词时将其存储到动态创建的数组中。创建一个并行整数数组来保存每个特定单词在文本文件中出现的次数。如果该词多次出现在文本文件中,请不要将其添加到您的动态数组中,但请确保在并行整数数组中增加相应的词频计数器。在进行任何比较之前,请删除所有单词中的任何尾随标点符号。
创建并使用以下包含 Bill Cosby 引用的文本文件来测试您的程序。
我不知道成功的关键,但失败的关键是试图取悦所有人。
在程序结束时,生成一个打印两个数组内容的报告
这是我的代码:
#include <iostream>
#include <fstream>
#include <string>
#include <cstring>
#include <cctype>
using namespace std;
int main()
{
ifstream inputFile;
int numWords;
string filename;
string *readInArray = 0;
char testArray[300] = {0};
char *realArray = 0;
const char *s1 = 0;
string word;
int j =1;
int k = 0;
int start =0;
int ending = 0;
char wordHolder[20] = {0};
cout << "Enter the number of words the file contains: ";
cin >> numWords;
readInArray = new string[(2*numWords)-1];
cout << "Enter the filename you wish to read in: ";
cin >> filename;
inputFile.open(filename.c_str());
if (inputFile)
{
cout << "\nHere is the text from the file:\n\n";
for (int i=0; i <= ((2*numWords) -1); i +=2)
{
inputFile >> readInArray[i]; // Store word from file to string array
cout << readInArray[i];
strcat(testArray, readInArray[i].c_str()); // Copy c-string conversion of word
// just read in to c-string
readInArray[j] = " ";
cout << readInArray[j];
strcat(testArray, readInArray[j].c_str()); // This part is for adding spaces in arrays
++j;
}
inputFile.close();
}
else
{
cout << "Could not open file, ending program";
return 0;
}
realArray = new char[strlen(testArray)];
cout << "\n\n";
for(int i=0; i < strlen(testArray); ++i)
{
if (isalpha(testArray[i]) || isspace(testArray[i])) // Is makes another char array equal to
{ // the first one but without any
realArray[k]=testArray[i]; // Punctuation
cout << realArray[k] ;
k++;
}
}
cout << "\n\n";
for (int i=0; i < ((2*numWords) -1); i+=2)
{
while (isalpha(realArray[ending])) // Finds space in char array to stop
{
++ending;
}
cout << "ending: " << ending << " ";
for ( ; start < ending; ++start) // saves the array up to stopping point
{ // into a holder c-string
wordHolder[start] = realArray[start];
}
cout << "start: " << start << " ";
readInArray[i] = string(wordHolder); // Converts holder c-string to string and
cout << readInArray[i] << endl; // assigns to element in original string array
start = ending; // Starts reading where left off
++ending; // Increments ending counter
}
return 0;
}
输出:
输入文件包含的字数:17
输入要读取的文件名:D:/Documents/input.txt
这是文件中的文本:
我不知道成功的关键,但失败的关键是试图取悦所有人。
我不知道成功的关键,但失败的关键是试图取悦所有人
结束:1 开始:1 I
结尾:6 开始:6 我没有
结尾:11 开始:11 我不知道
结尾:15 开始:15 我不知道
结尾:19 开始:19 我不知道钥匙
结尾:22 开始:22 我不知道钥匙>
结尾:29 开始:29 我不知道成功的关键
结尾:33 开始:33 我不知道成功的关键,但是↕>
我的问题:
最后一个 for 循环出了点问题,我运行它后它崩溃了。我包括了结束和开始变量,以帮助了解发生了什么。我知道有更好的方法来解决这个问题,但教练希望这样做。如果您知道我在最后一个 for 循环中出错的地方,任何帮助将不胜感激!
【问题讨论】:
-
请为您的问题选择一个更好的标题。它应该总结问题。
-
使用字符串和向量代替char数组和new;它更容易,所有这些问题都消失了。
标签: c++ string loops for-loop c-strings