【问题标题】:C++ Load Document Error. Trying to testC++ 加载文档错误。试图测试
【发布时间】:2014-05-03 19:43:35
【问题描述】:

我正在做一个课堂上的项目,它是一个文本分析项目。我们应该将一个文档加载到程序中并基本上从中读取数据。例如:(字数、句子数等)。出于某种原因,我的第一个函数无法正常工作:我的 loadDocument 函数应该将文档加载到程序中。

这是 main 中调用该函数的代码:

case 1: // Load Document
{
    string inputLoc;
    cout << "Please input the document name:" << endl;
    cin >> docName;
    myDocs[docCount].setName(docName);
    myDocs[docCount].id = docCount;
    cout << "Input Location: " << endl;
    cin >> inputLoc;
    myDocs[docCount].loadDocument(inputLoc);
    docCount++;
    break;
}

我已经在案例之外初始化了docName - 在它之前。

这是我的loadDocument 在我的Document 类中:

void Document::loadDocument(string name)
{
    ifstream myFile(name);
    int numOflines = 0;
    string theLine;
    char words;

    while (myFile.get(words))
    {
        switch (words)
        {
        case '.':
            numOflines++;
            break;
        case '?':
            numOflines++;
            break;
        case '!':
            numOflines++;
            break;
        }
    }

    lineCount = numOflines;
    setLineCt(numOflines);
    arr = new Line[lineCount];
    myFile.close();
    char theChar;
    ifstream myFile2(name);
    int key = 0;

    if (myFile2.is_open())
    {
        for (id = 0; id < lineCount; id++)
        {
            while (theChar != '.' || theChar != '!' || theChar != '?')
            {
                myFile2 >> noskipws >> theChar;
                theLine[key] = theChar;
                key++;
            }

            myFile2 >> theChar;

            arr[id].setStr(theLine);
        }
    }
}

我只是想知道我的loadDocument 是否有任何明显的错误?出于某种原因,它实际上并没有将文档加载到程序中。对于输入位置,我输入了要输入的文本文件的确切文件位置。例如:C:\Users\Documents------。在我输入之后,我的程序就进入了一个无限循环。

我的loadDocument 正在做它应该做的事情吗?它应该打开一个文档并从中提取句子的数量以及单词的数量。

另外,我是否通过像这样输入该文件位置来正确测试它?对不起,我是文件输入/输出的新手。

【问题讨论】:

    标签: c++ file input output


    【解决方案1】:

    您的while() 循环不正确:

    while (theChar != '.' || theChar != '!' || theChar != '?')
    

    || 在这里不是正确的条件运算符。如果一个条件为假,则其他两个条件为真,从而导致无限循环。你必须使用&amp;&amp;:

    while (theChar != '.' && theChar != '!' && theChar != '?')
    

    【讨论】:

    • 感谢您的回复!我改变了这一点,并意识到我为什么错了。谢谢。但由于某种原因,它仍然在我的菜单中无限循环。我测试正确吗?
    • @user3421510 我认为另一个问题是您没有在执行while() 循环之前检查您的输入是否成功。从循环中取出第一行并将其添加为条件,如下所示:while (myFile2 &gt;&gt; noskipws &gt;&gt; theChar &amp;&amp; theChar != '.' &amp;&amp; theChar != '!' &amp;&amp; theChar != '?')
    • 那么我必须从循环中删除 myFile2>>noskipws>>theChar 对吗?
    • @user3421510 正确。
    • 抱歉。由于某种原因,它仍然进入 main 中的无限循环。但这仅适用于案例 1。在案例 1 中一定有什么地方出了问题。我就是不知道是什么
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-13
    • 1970-01-01
    • 2021-06-13
    • 1970-01-01
    相关资源
    最近更新 更多