嘿,對不起,如果這是問了很多,但我不知道這裏的問題是什麼。這段代碼爲什麼不運行?
在下面的C++代碼中,我從用戶定義的輸入文件讀取並生成輸出。我一直在一塊一塊地編寫它,並將它放在一起,編譯,測試等,以便找出錯誤。這對我來說是一種學習體驗,我猜...
無論如何,當我運行代碼時,命令提示符會打印一行並且無響應。我會說它已經陷入某種循環,但我認爲這是不可能的。
我想可能有一些做與陣列我想聲明,我想作一個動態字符串數組,但我發現很難......
#include <iostream>
#include <fstream>
#include <algorithm>
#include <cctype>
#include <string>
using namespace std;
int wordCount(string line)
{
int fpos, fpos2;
int count = 0;
fpos = line.find_first_not_of(' ');
line.erase(0, fpos);
while(line.size() > 0)
{
fpos = line.find_first_of(' ');
if(line.at(0) == '"')
{
line.erase(0, 1);
for(int i = 0; i <line.size(); i++)
if(line.at(i) == '"' && line.at(i-1) != '\\')
{
fpos2 = i;
break;
}
line.erase(0, fpos2 + 2);
}
else
line.erase(0, fpos + 1);
count++;
}
return count;
}
int main()
{
//Current line; Input file; Output file;
string currentline, fileName, outFileName;
ifstream fin;
ofstream fout;
cout << "Enter input file name: ";
getline(cin, fileName);
cout << "Enter output file name: ";
getline(cin, outFileName);
fin.open(fileName.c_str());
if (!fin.good()) throw "I/O error";
fout.open(outFileName.c_str());
if (!fout.good()) throw "I/O error";
getline(fin, currentline);
while (!currentline.empty())
{
int pos, pos1;
pos = currentline.find("//");
string postScript = currentline.substr(pos+2,-1);
pos = currentline.find_first_of(';');
string xline = currentline.substr(0,pos+1);
cout << xline << endl;
int size = wordCount(xline);
string *words;
words = (string *) malloc (size*sizeof(string));
words = new string[size];
pos = xline.find_first_not_of(' ');
xline.erase(0, pos);
for (int i = 0; i < size; i++)
{
pos = xline.find_first_of(' ');
if (xline.at(0) == '"')
{
xline.erase(0, 1);
for(int a = 0; a < xline.size(); a++) //This for loop finds the end of a quoted statement within the line.
if (xline.at(a) == '"' && xline.at(a-1) != '\\')
{
pos = a;
break;
}
words[i] = xline.substr(0,pos);
xline.erase(0,pos + 2);
}
else
{
words[i] = xline.substr(0,pos);
xline.erase(0,pos + 1);
}
cout << words[i] << endl;
}
cout << xline << endl << endl;
getline(fin, currentline);
}
return 0;
}
您應該嘗試放入一些'cerr << xxx;'語句來查看執行過程中各個點的變量。不知道你的輸入是什麼,很難確切地說出程序失敗的地方 - 它充滿了潛在的錯誤。例如,substr()不應該有一個負的第二個參數;你只是假設find()成功; getline()應該檢查輸入是否成功 - 不要依賴當前行失敗時的空行 - 而且我只查看了三分之一的代碼。 – 2011-03-22 04:58:01