![](/img/trans.png)
[英]How to obtain the whole integers from file has strings and integers and store them into array in C++?
[英]C++: Read strings and integers from file, and obtain highest number
我编写了下面的代码,试图从文本文件中读取字符串和整数,其中整数是与其对应的字符串(玩家)的最高数字(分数)。 我能cout
文件的内容,但我怎么测试,数字是最高的,如何将其链接到它的播放器? 任何帮助将不胜感激,谢谢!
文本文件内容:
Ronaldo
10400
Didier
9800
Pele
12300
Kaka
8400
Cristiano
8000
代码:
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int main() {
string text;
string player;
int scores;
ifstream scoresFile;
// Open file
scoresFile.open("scores.txt");
// Check if file exists
if (!scoresFile) {
cerr << "Unable to open file: scores.txt" << endl;
exit(0); // Call system to stop
}
else {
cout << "File opened successfully, program will continue..." << endl << endl << endl;
// Loop through the content of the file
while (scoresFile >> text) {
cout << text << endl;
}
}
// Close file
scoresFile.close();
return 0;
}
制作一个变量string bestplayer
, string currentplayer
和int bestscore = 0
。 每次阅读一行时,我都会增加一个整数。 然后,您取其相对于 2 ( i % 2
) 的模数,如果它是奇数,则将流输出到currentplayer
。 如果是偶数,则将流输出为临时整数并将其与bestscore
进行比较。 如果它高于bestscore
,设定的值bestscore
于整数和集bestplayer = currentplayer
。 祝你好运!
非必要时不要使用exit()
。 exit()
不会做任何堆栈展开和规避 RAII 的原则。 在main()
您可以轻松使用return EXIT_FAILURE;
在出现错误时结束程序。
谈论 RAII:使用构造函数为class
赋值,例如。 使用std::ifstream scoresFile{ "scores.txt" }; instead of
std::ifstream scoresFile{ "scores.txt" }; instead of
scoresFile.open("scores.txt"); . Also, there is no need to call
. Also, there is no need to call
scoreFile.close()`,因为析构函数会处理它。
如果您只想说'\\n'
(或"...\\n"
),请不要使用std::endl
。 std::endl
不仅会在流中插入换行符( '\\n'
),还会刷新它。 如果你真的想刷新流,那么明确地写std::flush
而不是std::endl
。
现在到手头的问题。 优雅的解决方案是拥有一个代表player
的对象,该对象由玩家姓名及其分数组成。 这样的对象不仅可以用于读取高分列表,还可以在游戏过程中使用。
为了输入和输出,将重载流插入和提取运算符。
#include <cstdlib>
#include <iostream>
#include <string>
#include <fstream>
class player
{
std::string name;
int score;
friend std::ostream& operator<<(std::ostream &os, player const &p);
friend std::istream& operator>>(std::istream &is, player &p);
public:
bool operator>(player const &other) { return score > other.score; }
};
std::ostream& operator<<(std::ostream &os, player const &p)
{
os << p.name << '\n' << p.score;
return os;
}
std::istream& operator>>(std::istream &is, player &p)
{
player temp_player;
if (is >> temp_player.name >> temp_player.score)
p = temp_player; // only write to p if extraction was successful.
return is;
}
int main()
{
char const * scoresFileName{ "scores.txt" };
std::ifstream scoresFile{ scoresFileName };
if (!scoresFile) {
std::cerr << "Unable to open file \"" << scoresFileName << "\"!\n\n";
return EXIT_FAILURE;
}
std::cout << "File opened successfully, program will continue...\n\n";
player p;
player highscore_player;
while (scoresFile >> p) { // extract players until the stream fails
if (p > highscore_player) // compare the last extracted player against the previous highscore
highscore_player = p; // and update the highscore if needed
}
std::cout << "Highscore:\n" << highscore_player << "\n\n";
}
除了重载<<
运算符之外,您还可以采用更多的程序方法,只需检查读取的行中的第一个字符是否为数字,如果是,则使用std::stoi
转换为int
并与当前的最大值进行比较分数,如果更大则更新。
您的数据文件布局有点奇怪,但假设它是您必须使用的,您可以简单地将第一行读取为名字,并在读取循环结束时将名称存储为 say lastname
,以便它是当您在下一行读取整数时可用。
使用std::exception
来验证std::stoi
转换将确保您在进行比较和更新高分之前处理有效的整数数据,例如
// Loop through the content of the file
while (scoresFile >> text) {
if ('0' <= text[0] && text[0] <= '9') { /* is 1st char digit? */
try { /* try and convert to int */
int tmp = stoi (text);
if (tmp > scores) { /* if tmp is new high score */
scores = tmp; /* assign to scores */
player = lastplayer; /* assign lastplayer to player */
}
} /* handle exception thrown by conversion */
catch ( exception& e) {
cerr << "error: std::stoi - invalid argument or error.\n" <<
e.what() << '\n';
}
}
else /* if 1st char not a digit, assign name to lastplayer */
lastplayer = text;
}
另一个注意事项。 初始化要用于大于比较的变量时,应将值初始化为INT_MIN
以确保正确处理负值。 (对于小于比较,初始化为INT_MAX
)
总而言之,你可以做类似的事情:
#include <iostream>
#include <string>
#include <fstream>
#include <limits>
using namespace std;
int main() {
string text;
string player;
string lastplayer;
int scores = numeric_limits<int>::min(); /* intilize to INT_MIN */
ifstream scoresFile;
// Open file
scoresFile.open("scores.txt");
// Check if file exists
if (!scoresFile) {
cerr << "Unable to open file: scores.txt" << endl;
exit(0); // Call system to stop
}
cout << "File opened successfully, program will continue..." <<
endl << endl;
// Loop through the content of the file
while (scoresFile >> text) {
if ('0' <= text[0] && text[0] <= '9') { /* is 1st char digit? */
try { /* try and convert to int */
int tmp = stoi (text);
if (tmp > scores) { /* if tmp is new high score */
scores = tmp; /* assign to scores */
player = lastplayer; /* assign lastplayer to player */
}
} /* handle exception thrown by conversion */
catch ( exception& e) {
cerr << "error: std::stoi - invalid argument or error.\n" <<
e.what() << '\n';
}
}
else /* if 1st char not a digit, assign name to lastplayer */
lastplayer = text;
}
// Close file
scoresFile.close();
cout << "Highest Player/Score: " << player << "/" << scores << '\n';
return 0;
}
示例使用/输出
$ ./bin/rdnamenum2
File opened successfully, program will continue...
Highest Player/Score: Pele/12300
仔细检查一下,如果您还有其他问题,请告诉我。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.