我的问题是:如何将 first_In_Line 和 last_In_Line 变量传递到 for 循环之外,以便我的最终语句接收变量并正确显示?
我假设学生的名字不同。
// This program allows a user to define class size, between 1 and 25
// students, and give a list of names. It does not store a list
// of names, but does sort the names to determine alphabetically,
// which student will be first in line, and who will be last.
#include <iostream>
#include <string>
using namespace std;
int main()
{
// Non-user defined variables
int num_Students = 0;
string first_In_Line = "",
last_In_Line = "",
previous_Name = "";
bool compare = true;
// User defined variable.
string next_name;
// Get number of students from user between 1 and 25
cout << "Please enter the number of students in class between 1 and 25: ";
cin >> num_Students;
// Validate user input
while (num_Students < 1 || num_Students > 25)
{
cout << "Please enter a number between 1 and 25.";
cin >> num_Students;
}
for (int i = 1; i <= num_Students; i++)
{
cout << "What is the name of student " << i << "? ";
cin >> next_name;
if (compare == true)
{
if (next_name < previous_Name)
{
first_In_Line = next_name;
last_In_Line = previous_Name;
}
else if (next_name > previous_Name)
{
first_In_Line = previous_Name;
last_In_Line = next_name;
}
}
// Set compare to "true" to execute if statements next
// iteration of for-loop
compare = true;
previous_Name = next_name;
}
cout << first_In_Line << " is first in line." << endl;
cout << "And " << last_In_Line << " is last in line." << endl;
return 0;
}
输出是这样的,名字不正确:
请在1到25之间输入类(class)人数:3 学生 1 的名字是什么?亚当 学生 2 的名字是什么?马特 学生 3 的名字是什么? zed 马特排在第一位。 zed 排在最后。
最佳答案
您可以取消使用 previous_name 并只使用循环遍历您的名字。您只关心排在第一位和最后一位的人。
for (int i = 1; i <= num_Students; i++)
{
cout << "What is the name of student " << i << "? ";
cin >> next_name;
if (i == 1) // initialize your first entry as first and last in line (min, max)
{
first_In_Line = next_name;
last_In_Line = next_name;
}
else // compare for last and first in line (min, max) after first iteration of for loop
{
if (next_name > last_In_Line)
last_In_Line = next_name;
else if (next_name < first_In_Line)
first_In_Line = next_name;
}
}
关于C++ for 循环字符串比较逻辑存在缺陷,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32722159/