void displayFile()
{
char userInput[20];//Used to store the typed input commands from the user.
ifstream ip("D:\\H Drive ITT\\Level 8 Degree\\Software Dev (Andrew)\\MiniProject\\about.txt");//Input from file
string line ;//Store each line in the string
int exit = 0;//Used to hold the value which indicates whether or not the function should end determined by the user.
if (ip)//ip is true if the file exists.
{}
else
{
cout << "-Error_File_Not_Found" << endl;
}
while (!ip.eof())//Scan till end of file
{
ip >> line;
cout << line << endl;
}
cout << "Type exit to return" << endl << endl << ">>>" ;
do {
cin >> userInput;
if (strcmp(userInput, "exit") == 0 || strcmp(userInput, "EXIT") == 0 || strcmp(userInput, "eXIT") == 0 || strcmp(userInput, "Exit") == 0)
{
exit = 1;
}
else
{
exit = 0;
}
} while (exit !=1);
ip.close();
}
//The
//output
//displays
//like
//this.
当代码运行时,它会接收段落并在其自己的行上显示每个单词。我见过涉及类的解决方案,但我还需要一个不同的解决方案,因为我还没有上过类。
答案 0 :(得分:2)
这里有两个问题。
>>
运算符不读取行,它在空格上停止。使用std::getline
作为Ramana在评论中建议。eof()
。它在之后返回true ,你已经读过文件末尾,而不是之前你会读到结束。所以你的循环会迭代一次太多。最好的方法是使用std::getline
的返回值作为循环条件。