我需要创建一个程序,它接受由空格分隔的整数输入,例如:
4 4 5 8 8 9
程序然后获取这些数字并计算每个数字的出现次数,因此上述输入的输出将为:
The number 4 has 2 occurrence(s)
The number 5 has 1 occurrence(s)
The number 8 has 2 occurrence(s)
The number 9 has 1 occurrence(s)
我几乎想到了这一点,当我为数字没有空格分隔的输入(假设它们是1位整数,而不是我为最终版本制作的假设)时,它工作得很好但是一旦输入在数字之间有空格,它就不再有效。
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <vector>
#include <string>
using namespace std;
vector<int> parseString(string &s);
void parseVector(vector<int> &v);
int checkRepeats(vector<int> &v, int n);
void printVector(vector<int> &v);
int main()
{
vector<int> parsed;
vector<int> numbers;
string input;
bool keepGoing = true;
int nRepeats; // stores the number of times a number occurs, will constantly be overwritten
cout << "Enter some numbers: ";
while(true)
{
cin >> input;
if(input == "stop" || input == "Stop")
{
break;
}
parsed = parseString(input); // parse input string to vector of ints
parseVector(parsed); // send vector of ints to be checked for repeats
//printVector(parsed);
//cout << "\n";
}
}
void printVector(vector<int>&v) // not called right now, used for testing
{
for(int i = 0; i < v.size(); i++)
{
cout << v.at(i) << " ";
}
}
void parseVector(vector<int> &v)
{
int x = 0;
int j = 0;
int nRepeats = 0;
int size = v.size();
for(int i = 0; i < size; i++)
{
x = v.at(i); // x equals the next element in vector 'v'
nRepeats = checkRepeats(v, x); // count the number of times number 'x' occurs in vector 'v'
//i += nRepeats - 1;
cout << "The number: " << x << " has: " << nRepeats << " occurrence(s)\n";
}
}
int checkRepeats(vector<int> &v, int n) // counts the number of times a number is found in a given vector
{
int nTimes = 0;
int size = v.size();
for(int i = 0; i < size; i++)
{
if(v.at(i) == n) // match found, increment counter
{
nTimes++;
}
}
return nTimes;
}
vector<int> parseString(string &s)
{
vector<int> v;
int strLen = s.size();
int x;
for(int i = 0; i < strLen; i += 2) // increment by 2 to cut out white space from between the numbers
{
x = s.at(i);
x -= 48; // subtract 48 from x, converts from ascii to int value
v.push_back(x);
}
return v;
}
如果你转到该代码的第88行,并将循环计数器的增量从i += 2
更改为i++
,它将完美地用于没有空格的输入,例如445889
而不是4 4 5 8 8 9
有谁知道我可以尝试解决这个问题?
答案 0 :(得分:5)
您可以尝试使用地图(超级天真版本:)
#include <map>
#include <iostream>
int main()
{
int i;
std::map<int, int> ints;
while (std::cin >> i)
++ints[i];
for (auto const& num : ints)
std::cout <<
"The number " <<
num.first <<
" has " <<
num.second <<
" occurrence(s)\n";
}
答案 1 :(得分:0)
cin
从标准输入读取,直到它碰到空格字符,因此您需要重新思考如何填充矢量。除此之外,代码应该可以正常工作。