下面的字符串是說明: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