【问题标题】:Working with ifstream, data within file being called does not print使用 ifstream,被调用文件中的数据不打印
【发布时间】:2018-12-21 09:15:19
【问题描述】:

这是我的代码,目标是打开一个文件,读取该文件中的单词并计算该文件中有多少个字符串。我的问题是,当我运行我的程序并调用测试文件时,只读取和打印该文件的第一个字符串,我不确定它出了什么问题,任何帮助都会很棒。

这是我的测试文件中的内容:

这个 &%file 应该!!,...

正好有 7 个字。


#include <iostream>
#include <fstream>
#include <string>

using namespace std;

int main(){

    ifstream inputFile;
    string fileName, inputRead;
    string sentinel = "quit";
    int count = 0;

    cout<< "what file do you want to open?: ";
    cin>> fileName;

    inputFile.open(fileName);

    while(!inputFile){
        cout<< "\nError opening file." <<endl;

        cout<< "Please enter filename correctly: ";
        cin>> fileName;

        inputFile.open(fileName);

    }

    while(fileName != sentinel){
        if(inputFile){

            inputFile >> inputRead;

            count++;

            cout<< endl;
            cout<< fileName << " data" <<endl;
            cout<< "*********************************\n" <<endl;

            cout<< inputRead <<endl;

            cout<< "\n*********************************" <<endl;
            cout<< fileName << " has " << count << " words." <<endl;

            cout<< "\nEnter another file name or type \"quit\" to end: ";
            cin>> fileName;
        }
    }

    inputFile.close();

    cout<< endl;

}

【问题讨论】:

  • 当您说只打印第一个字符串时,您是指在提示您输入更多输入之前只打印第一个单词,还是无论输入多少次都不会产生更多输出文件名?
  • 无论我输入多少次文件名都不会产生更多输出,一旦我输入文件名,它会打印第一个字符串,然后再次提示我输入另一个文件名l
  • 你在主循环之前调用inputFile.open(fileName);。它只成功一次。为什么你希望能够在主循环中读取多个文件? cin&gt;&gt; fileName; 不会导致文件重新打开。
  • 啊啊啊谢谢,我刚开始学C++,习惯了它的逻辑,能跟得上程序

标签: c++ string xcode9 ifstream


【解决方案1】:

问题在于 while 循环中的 if 语句。如果文件名不等于 sentinel,则检查 inputFile 是否有效。如果是这样,您在获得新文件名之前只执行一次里面的代码行。你想要的是这样的:

while(fileName != sentinel){
    cout<< endl;
    cout<< fileName << " data" <<endl;
    cout<< "*********************************\n" <<endl;
    while(inputFile >> inputRead){

        count++;


        cout<< inputRead <<endl;

    }
    cout<< "\n*********************************" <<endl;
    cout<< fileName << " has " << count << " words." <<endl;

    cout<< "\nEnter another file name or type \"quit\" to end: ";
    cin>> fileName;
}

【讨论】:

  • 不要忘记读取操作可能会失败。在使用之前,您必须检查读取是否有效。最好的方法是将读取作为 while 条件的一部分。为你修复了上面的代码。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多