【发布时间】:2015-09-23 01:05:56
【问题描述】:
从文件中读取和最小/最大逻辑。
随着更多信息的到来,我将每 30 分钟更新一次我的问题、陈述和代码,因此我的编辑速度不会超过某些人的回答速度。
我的问题是,如何设置程序一次读取一个名称而不连接名称?
该文件是一个 .txt 文件,内容如下: Jackie Sam Tom Bill Mary Paul Zev Barb John
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
// File stream objects
ifstream inputFile;
inputFile.open("LineUp.txt");
// Non-user variables
string first_In_Line = "",
last_In_Line = "",
previous_Name = "",
next_name = "";
if (inputFile)
{
// Display message to user
cout << "Reading file... \n";
while (inputFile >> next_name)
{
cout << next_name;
if (next_name > last_In_Line)
{
first_In_Line = last_In_Line;
last_In_Line = next_name;
}
else if (next_name < first_In_Line)
{
last_In_Line = first_In_Line;
first_In_Line = next_name;
}
// This else clause should only apply to the first iteration
else
{
first_In_Line = next_name;
}
}
//Close the file
inputFile.close();
// Display first in line and last in line
cout << first_In_Line << " is first in line." << endl;
cout << "And " << last_In_Line << " is last in line." << endl;
}
else
{
// Display error message.
cout << "Error opening the file.\n";
}
return 0;
}
输出是: 正在读取文件... JackieSamTomBillMaryPaulZevBarbJohnJohn 排在第一位。 山姆排在最后。
【问题讨论】:
-
你应该做的是将所有的名字保存到一个数组中然后你安排它们..这样会节省很多时间
-
我还没开始学习数组。
-
您在阅读名称时一次显示一个名称,中间没有任何空格。
-
进行编辑 - 谢谢
标签: c++ variables text-files fstream string-comparison