D
D
Denis Kuznetsov2018-03-29 00:34:48
C++ / C#
Denis Kuznetsov, 2018-03-29 00:34:48

Why doesn't it exit the loop?

#include <iostream>
#include <fstream>
#include <string>

using namespace std;

int main()
{
  ifstream in("E:\\f.txt");
  ofstream out1("E:\\h.txt"), out2("E:\\g.txt");
  if (!in)
  {
    cout << "Error" << endl;
    system("pause");
    return 0;
  }
  string s;
  s += ' ';
  while (in.peek() != EOF)
  {
    getline(in, s, '#');
  }
  string sub;
  int space = 0; 
  string::size_type len = s.size();
  for (unsigned int i = 0; i < len; i = space + 1)
  {
    space = s.find(' ',  i); 
    sub = s.substr(i, space - i);
    if (sub[0] == '-')
    {
      out1 << sub << ' ';
    }
    else
    {
      out2 << sub << ' ';
    } 
  }
  in.close();
  out1.close();
  out2.close();
  system("pause");
  return 0;
}

loops at the moment of selecting a substring, everything seems to be fine, looks for a space between numbers, selects a substring, from the beginning of the search to the space, checks the number for negativity, moves the marker to the next element after the space and starts searching from it

Answer the question

In order to leave comments, you need to log in

1 answer(s)
C
Codebaker, 2018-04-24
@DennisKingsman

You don't check for std::npos result in space:
space = s.find(' ', i);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question