【发布时间】:2019-06-14 21:53:28
【问题描述】:
您能否就如何简化代码给我一些建议?
#include <iostream>
#include<fstream>
#include<string>
using namespace std;
int main() {
string current_users[5];
string new_users[5], new_user;
ifstream read;
read.open("current.txt");
for (int index = 0; index < 5; index++) {
read >> current_users[index];
}
read.close();
cout << "Enter a username: ";
cin >> new_user;
char user_choice;
int index = 0, new_index = 0;
while (index <= 5) {
if (new_user == current_users[index]) {
cout << "That username already exists."
<< " Enter a different username: ";
cin >> new_user;
index = 0;
continue;
}
if (index < 5)
index++;
else {
new_users[new_index] = new_user;
cout << "\nWelcome " << new_user << endl;
new_index++;
if (new_index < 5) {
cout << "Would you like to register another user?:"
<<"'Y' for yes or 'N' for no";
cin >> user_choice;
}
if (user_choice == 'Y' || user_choice == 'y') {
cout << "\nEnter a new username: ";
cin >> new_user;
index = 0;
}
else
break;
}
}//end of while
system("pause");
return 0;
}
此程序要求用户输入用户名并检查该用户名是否已存在。如果存在,它会提示用户使用不同的用户名,同时检查该用户名是否已经存在。如果用户名是唯一的,程序会欢迎新用户并询问用户是否想注册另一个新用户(很奇怪,但我想尝试一下)。如果用户想将另一个用户添加到“网站”,那么程序会再次运行,检查冗余。我将此程序限制为 5 个可能的用户名,以便检查和添加以方便测试。没有错误。
代码很粗。我想出了这个问题。我不在学校。负担不起,也没有被我申请的任何学校录取。对提供计算机科学学位的在线学校有何建议?
【问题讨论】:
-
std::vector可以提供帮助。 -
这个问题可能更适合codereview.stackexchange.com
StackOverflow更多的是关于您想要修复的损坏代码。CodeReview是关于你想要改进的工作代码。 -
半相关:不要将短而复杂的代码与好的代码混为一谈。很多时候,短而愚蠢是正确的方法。简短是因为不存在的代码没有错误,而愚蠢是因为它易于阅读、调试和维护。缩短的关键之一是利用其他人的代码,尤其是标准库。只有在愚蠢不符合要求时才使事情复杂化。
标签: c++ visual-c++ c++14