【发布时间】: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>> fileName;不会导致文件重新打开。 -
啊啊啊谢谢,我刚开始学C++,习惯了它的逻辑,能跟得上程序
标签: c++ string xcode9 ifstream