下面的字符串是说明:for循环与不工作
编写一个程序,在同一时间在一个文本文件中的一个字读。第一次遇到时,将一个单词存储到动态创建的数组中。创建一个平行整数数组来保存每个特定单词在文本文件中出现的次数。如果该文字多次出现在文本文件中,请不要将其添加到动态数组中,但要确保在并行整数数组中增加相应的文字频率计数器。在进行任何比较之前,从所有单词中删除任何尾随的标点符号。
创建并使用包含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
输入文件n AME你想阅读:d:/Documents/input.txt
下面是从文件中的文本:
我不知道关键sucess,但关键要失败试图取悦每一个人。
我不知道钥匙sucess但关键要失败的试图取悦所有人
结局:1点开始:1我
结束:6开始:6我不
结束: 11开始:11我不知道
结束:15开始:15我不知道
结束:19开始:19我不知道密钥
结束:22开始:22我不知道钥匙>
结束:29开始:29我不知道钥匙sucess
结束:33开始:33我不知道钥匙sucessbut↕>
我的问题:
某处有问题,最后一个for循环,我运行后,它崩溃。我包含了结尾和起始变量,可能有助于了解发生了什么。我知道有更好的方法来解决这个问题,但教练希望这样做。如果你知道我最后一个for-loop出错的地方,任何帮助都将非常感谢!
请为您的问题选择一个更好的标题。它应该总结这个问题。 – meagar 2015-02-08 03:23:39
使用字符串和向量来代替char数组和new;这很容易,所有这些问题都会消失。 – 2015-02-08 03:30:11