【问题标题】:Why this C++ program is not printing anything?为什么这个 C++ 程序不打印任何东西?
【发布时间】:2020-08-29 12:57:02
【问题描述】:

我有这个 C++ 程序,但它没有在控制台中打印任何内容。 我将字符串的内容复制到 2 个向量中并对它们进行计数递增操作。

#include <iostream>
#include<vector>
#include<bits/stdc++.h>
#include<string>
using namespace std;

int main()
{
  string s;
  cin>>s;
  int i,j;
  vector<char> a;
  vector<char> b;
  int count1=0;
  int count2=0;
  int count3=0;
  int t=s.length()/2;
  for(i=0;i<t-1;t++)
  {
      a.push_back(s[i]);
  }
  for(j=t;j<s.length();j++)
  {
      b.push_back(s[j]);
  }
        int e1,e2;
  for (auto it1 = a.begin(), it2 = b.begin();
     it1 != a.end() && it2 != b.end(); 
     ++it1, ++it2)
  {
      if(int(*it1)>int(*it2))
         count1++;
 
      if(int(*it1)<int(*it2))
         count2++;
 
      if(int(*it1)==int(*it2))
         count3++;
  }
  
  cout<<min(min(count1,count2),count3);
}

最后我打印了三个计数中的最小值。

【问题讨论】:

  • 你试过调试你的程序吗?另外,#include&lt;bits/stdc++.h&gt; 是不好的做法。
  • 您可以(至少暂时)计算中间结果。示例: out
  • 请提供minimal reproducible example(您非常接近)。缺少的是输入和预期输出以及实际输出的示例。
  • 您尝试在几个地方比较不同符号的整数。您应该养成启用更多编译器警告的习惯,例如。 [警告:不同符号的整数表达式的比较:'int' ....} [-Wsign-compare] ]

标签: c++ string algorithm vector data-structures


【解决方案1】:

我发现你的代码在下面陷入了无限循环。

for (i = 0; i < t - 1; t++)   // not t++, but it should be i++
{
    a.push_back(s[i]);
}

我也相信调试技能可以帮助您发现程序中的错误。

【讨论】:

    【解决方案2】:

    在您插入cin&gt;&gt;s; 之后,程序继续等待插入数据,在变量string s 上插入数据之后,但在此之后,您的代码似乎不清楚其目标,因为对于多个输入,您的方法与internal if 基本上什么都做不了,你最初的目标是什么?

    在你的 for 中有一个循环。 将您的原始块引用覆盖为:

      int t=s.length()/2;
      for(i=0;i<t-1;i++)
      {
          a.push_back(s[i]);
      }
    

    【讨论】:

    • 输入字符串后按回车,必须执行正确吗?
    • 是的,我现在相信这种对代码的覆盖足以打印正确的目标,当我插入“aafdsfsadfsdfasdfsdfs”时,输出为“3”,dfs 似乎是正确的
    • 是的,这只是一个愚蠢的错误。很抱歉给你们带来了困扰。
    猜你喜欢
    • 2019-05-18
    • 1970-01-01
    • 2013-04-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-12
    • 2015-08-23
    • 2012-12-30
    相关资源
    最近更新 更多