该程序涉及从关联的文本文件向用户输出笑话和妙语。笑话文件应该显示文件的全部内容,而穿孔文件应该只显示最后一行文本(前面的行是随机字符,不能被enter code here
读取)。
我遇到的问题是笑话文件内容在多行上输出,而它应该都在同一行。这是笑话文件的内容。
我开了一个名为999兆字节的乐队......
输出如下......
I
started
a
band
called
999
megabytes...
妙语文件正在从最后一行读取,但只显示行中的最后一个单词。这是文件的内容......
asfasdfasdfasdfsdf
asdfasdfsadfsadfsadf
asdfsadfsdfsdf
We haven't gotten a gig yet.
Here is what is outputting to the screen...
yet.
I have checked the file for any odd carriage return line feeds, but none are present that would explain this. Any assistance is tremendously appreciated, as I have been plugging away at this for hours to no avail.
Here is my code...
/*Include Section*/
#include <iostream>
#include <string>
#include <fstream>
#include <iomanip>
#include <cctype>
/*Namespace Section*/
using namespace std;
/*Function Prototypes Section*/
void displayAllLines(ifstream &inFile);
void displayLastLine(ifstream &infile);
/*Main section: this is the entry point of the program, which controls the flow of execution*/
int main()
{
string file1;
string file2;
ifstream joke;
ifstream punchline;
char decision;
char y;
char n;
/*Beginning of program. Prompts user, asking them if they are ready to proceed. If yes, will display the joke\punchline. If no,
ends program sequence*/
cout << "*******************************************************************************" << endl;
cout << setw(48) << "Punchline Program" << endl;
cout << "*******************************************************************************" << endl;
cout << endl;
cout << "Welcome to the Punchline Program!" << endl;
cout << "Are you ready to hear a joke? (y or n): ";
cin >> decision;
if (decision == 'y')
{
cout << endl;
cout << "Great! Prepare to laugh!" << endl;
cout << endl;
}
else if (decision == 'n')
{
cout << endl;
cout << "Ah, no sense of humor, I see. Time to make like a tree and leaf (queue rimshot)!" << endl;
exit(EXIT_FAILURE);
}
/*When user chooses "y", the following opens joke and punchline text files, outputting them to the user. The punchline file will
only display the last line of the file to the user*/
joke.open("joke.txt");
punchline.open("punchline.txt");
cout << endl;
displayAllLines(joke);
displayLastLine(punchline);
cout << endl;
system("PAUSE");
}
void displayAllLines(ifstream &infile)
{
string text;
while (infile >> text)
{
cout << text << endl;
}
}
void displayLastLine(ifstream &infile)
{
string text;
while (infile >> text);
{
cout << text << endl;
}
}
答案 0 :(得分:0)
while (infile >> text);
operator>>
没有阅读整行文字。它读取一个以空格分隔的单词。这就是为什么你最终只显示文件中的最后一个单词。你正在读错文件。
读取整行文本的正确函数是std::getline()
:
string text;
string lastline;
while (getline(infile, text))
lastline=text;
cout << lastline << endl;