【问题标题】:read unknown numebr of lines c++读取未知行数c ++
【发布时间】:2013-09-28 23:51:48
【问题描述】:

我从Read an unknown number of lines from console in c++ 得到了我的问题的答案。但是,该解决方案仍然对我不起作用。请帮我。这是我为某个问题实现的完整代码。它的第一块是读取多行的代码。

    #include<iostream>
    #include<string>
    #include<stdlib.h>
    #include<vector>

    using namespace std;

    int main()
    {
      vector<int> numbers;
      string line;
      int num = 0,rem = 0,count=0;
      while(getline(cin,line))
      {
       if(line.empty())
       {
//      cout<<"line check successful"<<endl;
        break;
       }
       numbers.push_back(atoi(line.c_str()));
      }
      cout<<endl;
      for(int i =0;i<numbers.size();i++)
      {
      num = numbers[i];
      for(int j=1;j<=num;j++)
      {
        while(j)
        {
            rem = j % 10;
            if(rem != 3 || rem !=7 || rem!=9)
            {
                j = j/10;
                continue;
            }
            count ++;
            j = j/10;
        }
    }
    cout<<count<<endl;
    count = 0;
}

}

它的第一部分是读取未知行数的算法。但是,在空返回或不输入任何输入的情况下按 Enter 键,循环不会停止。你能指出哪里出错了。?提前致谢。

【问题讨论】:

  • 题目与题目无关,检查你的数学以摆脱无限循环
  • 你调试过你的代码吗?打印一些变量。
  • @yngum 请检查第一个块。这就是我从控制台读取输入行的地方。那个无限循环必须停止我们输入。我希望现在很清楚。

标签: c++ input


【解决方案1】:

看看你的这部分代码:

for(int j=1;j<=num;j++)
{
  while(j)

while 循环直到 j 为 0 才停止,然后进入 for 循环并递增 j,因此 j 现在为 1,但 while 循环再次运行直到 j 为 0,因此您将永远循环。

【讨论】:

  • 感谢您的指出。但我的问题甚至在那之前。上面的while循环。那个循环没有退出。
  • @LakshmiNarayanan:你怎么知道它没有退出?
  • if 中的那个 cout 语句没有执行。这就是我评论它的原因。出于某种原因,我现在又试了一次,它奏效了。是的,您指出的问题是正确的。谢谢。
猜你喜欢
  • 2015-08-01
  • 2012-06-23
  • 1970-01-01
  • 2011-12-20
  • 2021-09-14
  • 1970-01-01
  • 2013-02-12
  • 2023-03-04
  • 1970-01-01
相关资源
最近更新 更多