gpt4 book ai didi

C++ 不在输出中打印重复数字

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:09:45 27 4
gpt4 key购买 nike

我必须读入一个 .txt 文件,其中包含用于确定谁将赢得模拟选举的选票。这是文件的一小部分,以便您了解。

1YYYYYYYYYYThe New Guy
2YNYNYNYNYNHarry Potter
2YNNYYNNYYNHarry Potter
2NNNNNNNNNNThe New Guy
3NYNYNYNYNYThe New Guy
3YYYYYYYYYYHarry Potter
3YYYYYYYYNYHarry Potter

第一个数字是“ID”号,如果它们是该数字的任何重复项,我不应该将其读入输出。数字列表一直到 99,重复项分散在整个文件中显示。不过,这些数字都是有序的。因此它可以如图所示变为 1222333,但不能变为 122332。这是我到目前为止的代码,循环在遇到第一个重复项时就停止了,我们将不胜感激。

#include <iostream>
#include <iomanip>
#include <fstream>
#include <sstream>
#include <limits>
#include <cstdio>
#include <string>
int main()
{
int ID; //pirate ID number
int IDTest;
char ch1, ch2, ch3, ch4, ch5, ch6, ch7, ch8, ch9, ch10; //vote on amendments
std::string vote; //vote for captain
std::ifstream fileReader; //open file for reading
fileReader.open("BallotsHogwart.txt");
if (fileReader.fail())
{
std::cout << "The ballots failed to open with code: " << fileReader.failbit;
}
else
{
do
{
IDTest = ID;
fileReader >> ID;
if (IDTest != ID)
{
std::cout << "Id:" << ID;
fileReader >> ch1;
fileReader >> ch2;
fileReader >> ch3;
fileReader >> ch4;
fileReader >> ch5;
fileReader >> ch6;
fileReader >> ch7;
fileReader >> ch8;
fileReader >> ch9;
fileReader >> ch10;
std::cout << " char 1 - 10: " << ch1 << ch2 << ch3 << ch4 << ch5 << ch6 << ch7 << ch8 << ch9 << ch10;
getline(fileReader,vote);
std::cout << " the votee: " << vote << std::endl;
}
} while(!fileReader.eof());
}
fileReader.close();
return 0;

最佳答案

使用getline()复制ID时需要忽略该行

代码如下:

#include <iostream>
#include <iomanip>
#include <fstream>
#include <sstream>
#include <limits>
#include <cstdio>
#include <string>
int main() {
int ID = 0; //pirate ID number
int IDTest;
char ch1, ch2, ch3, ch4, ch5, ch6, ch7, ch8, ch9, ch10; //vote on amendments
std::string vote; //vote for captain
std::string ignore; //ignore
std::ifstream fileReader; //open file for reading
fileReader.open("asdas.txt");
if (fileReader.fail())
{
std::cout << "The ballots failed to open with code: " << fileReader.failbit;
}
else
{
do
{
IDTest = ID;
fileReader >> ID;
if (IDTest != ID)
{
std::cout << "Id:" << ID;
fileReader >> ch1;
fileReader >> ch2;
fileReader >> ch3;
fileReader >> ch4;
fileReader >> ch5;
fileReader >> ch6;
fileReader >> ch7;
fileReader >> ch8;
fileReader >> ch9;
fileReader >> ch10;
std::cout << " char 1 - 10: " << ch1 << ch2 << ch3 << ch4 << ch5 << ch6 << ch7 << ch8 << ch9 << ch10;
getline(fileReader, vote);
std::cout << " the votee: " << vote << std::endl;
}
else {
getline(fileReader, ignore);
}
} while (!fileReader.eof());
}
fileReader.close();
std::cin.get();
return 0;
}

关于C++ 不在输出中打印重复数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43791509/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com