从没有定界符的文件中读取数字出现次数 C++

read number occurrence from file with no delimiter c++

我有一个工作原型,其中包含从文件中读取的代码。我的问题是弄清楚如何在没有任何空格的情况下从文件中读取它。为了让下面的代码正常工作,文件的内容需要如下所示: 3 4 6 2 5

我要放入文件的是: 34625

对于我的输出,我希望这样:

3 出现 4 次
4 出现 5 次
5 出现 6 次
6 出现 7 次

我也想知道是否有一种方法可以在不初始化数组的情况下打印数字。在我的代码中,文件中的数字为 12。但是有没有办法让 "unknown" 以防万一以后用户想要添加更多整数以从文件中读取?

#include <iostream>     
#include <fstream>
using namespace std;

//NEEDS to read numbers WITHOUT SPACES!!
int main()
{
  ifstream theFile ("inputData.txt");
  int MaxRange= 9;
  char c;
  int myint[12]={0};
  int mycompare[12]={0};
  int mycount[12] = {0};
  int i = 0, j = 0, k = 0;
  for(j=0;j <= MaxRange;j++){
    mycompare[j] = j;
  }

  do
  {
    theFile>>myint[i];
    for(j=0;j<=MaxRange;j++)
    {
      if(myint[i] == mycompare[j])
        mycount[j] = mycount[j]+1;
    }
    i++;
  }
  while((myint[i] >=0) && (myint[i] <= MaxRange));

  for(j=0; j <=MaxRange; j++)
  {
    if(isdigit(j)) 
      ++j;
    cout<< j<< " occurs: "<<mycount[j]<<endl;  
  }
}

为什么不使用char类型读取文件?使用 char,您可以逐字符读取并计算它们。使用 switch-case 结构而不是 "for" 来计数可能更好。 最后一段我不太清楚。

免责声明 - 以下代码未经编译或测试。你按原样打开它,你得到你得到的。

请注意我如何更改读取的文件 (cin) 以使用字符而不是整数。这允许我一次读取文件 1 个字符。另请注意,我已将范围更改为 10,因为有 10 个可能的数字(记住 0),并将我的计数数组设置为此大小。另请注意,这适用于任何文件大小,但如果在 32 位系统上文件中有超过 20 亿个 1 值的整数(整数溢出),它可能会失败。

#include <iostream>     
#include <fstream>
using namespace std;

int main()
{
  ifstream theFile ("inputData.txt");
  const int MaxRange= 10;
  char c;
  int mycount[MaxRange] = {0};

  // Check for eof each loop.  This may not be the best way to do this, 
  // but it demonstrates the concept.

  // A much better way is to put the cin assign right in the while loop parenthesis- 
  // this replaces and catches the eof automatically.
  while(!cin.eof())
  {
    theFile>>c;

    // If the char isn't a digit, we ignore it.
    if(!isdigit(c))
      continue;

    // Convert char to integer.
    int value = c + '0';

    // Update count array.
    mycount[value]++;
  }

  // Print the final array for each value.  You could skip counts
  // of zero if you would like with a little extra logic.
  for(int j=0; j<MaxRange; j++)
  {
    cout<< j<< " occurs: "<<mycount[j]<<endl;  
  }
}

开始的简单示例(用文件更改 cin

#include <iostream>
#include <map>
using namespace std;

int main() {
    map<int, int> m;
    char c;
    while (cin >> c)
        m[c - '0']++;
    for (auto i : m)
        cout << i.first << " occurs " << i.second << " times" << endl;
    return 0;
}

输入

34625

输出

2 occurs 1 times
3 occurs 1 times
4 occurs 1 times
5 occurs 1 times
6 occurs 1 times