程序输出不正确,具体取决于标准输入

时间:2014-02-18 03:20:34

标签: c++

我正在努力完成以下任务:

  1. 从标准输入中读取令牌流(使用面向令牌的输入)
  2. 挑选出拉链代码,假设是5个字符的字符串,前面是代码“zip:”。
  3. 该程序按频率降序打印前10个最常出现的邮政编码及其频率。
  4. 当我的标准输入看起来像我的代码似乎正在编译:zip:22333 zip:23423 zip:22333等。

    但是我们得到了一些它应该用于

    的示例代码
        city: Sherwood Park zip: T8C 1C3 $20.00 <87.3197428190@982662399.XmT.srvr@n325.xnot.com> cc: visa addr: 4811-100 Prudential Drive     =4=Z city: Toronto zip: M1P 4V4 $25.00    
    <8708.37428190@62986095171.XmT.srvr@n325.xnot.com> cc: visa addr: Box 484 =4=Z city: Clyde zip: T0G 0P0 $20.00 <8869.37428190@62987268014.XmT.srvr@n326.xnot.com> cc: visa addr: 490 E. Madison St.  =4=Z 3220 Hunt House
    

    当使用示例代码时,而不是以频率的降序显示拉链的输出,而它们的频率就是它们,我得到3 0 0 0 0 0 0 0 0 0(由于某种原因指示计数为3然后没别的了。)

    我知道路线和文件邮政编码之间存在差异,即文件存储如zip:39450,zip和数字之间有空格。如何修改while(!cin.fail())的内部以解决这个问题,并使用面向标记的输入将zipcode计算为距离“zip:”一个空格?请注意,我们不应该计算一些非美国的邮政编码。

    谢谢!

    #include <iostream>
    #include <fstream>
    #include <string>
    
    using namespace std;
    
    int main()
    {
        int i=0, n=0, l=0, c=0, temp2, flag=1;
        string zipsstring, zipsstringf, temp1;
        string stringarray[10000];
        int countarray[10000]={0};
        cin >> zipsstring;
        while(cin.get() && !cin.fail())
        {
            if(zipsstring.find("zip:", n != std::string::npos))
            { 
                zipsstringf=zipsstring.substr(4, 5);
                for(int i=0; i<=n; i++)
                {
                    if(stringarray[i]==zipsstringf)
                    {
                        countarray[i]+=1;
                        c=1;
                        break;
                    }
                }
    
                if(c==0)
                {
                    stringarray[n]=zipsstringf;
                    countarray[n]+=1;
                    n++;
                }
    
    
            }
            cin >> zipsstring;
        }
    
        for(int i=0; i<n && flag; i++)
        {
            flag=0;
            for(int j=0; j<n-1; j++){
                if(countarray[j+1]>countarray[j])
                {
                    temp1=stringarray[j];
                    temp2=countarray[j];
                    stringarray[j]=stringarray[j+1];
                    countarray[j]=countarray[j+1];
                    stringarray[j+1]=temp1;
                    countarray[j+1]=temp2;
                    flag=1;
                }
            }
        }
    
        for(int x=0; x<10; x++)
        {
            cout << stringarray[x] << " " << countarray[x] << endl;
        }
    
        return 0;
    }
    

1 个答案:

答案 0 :(得分:0)

如果你这样做是为了实际使用(而不是禁止使用正确工具的家庭作业),我会使用正则表达式库来完成这项工作:

std::regex w("[Zz]ip:[ \t\n]*[0-9]{5}");
while (std::getline(std::cin, line)) {

    std::copy(std::sregex_token_iterator(line.begin(), line.end(), w),
        std::sregex_token_iterator(),
        std::ostream_iterator<std::string>(std::cout, "\n"));
}

当然,有了这个,很明显你所做的事情基本上只是对grep的特定调用,但有时这就是生活。

相关问题