1

so I have a text file that contains formatted information as shown below.

100
4,2
3
5,1

I am trying to use the getline() function to read in each line, and then determine if that line has one or two numbers. My question is, How do I check if the line has two number or one? It would involve checking for a comma, but I have no idea on how to do so.

Thanks

Barmar
  • 741,623
  • 53
  • 500
  • 612
Dark
  • 323
  • 2
  • 5
  • 13
  • 1
    possible duplicate of [How can I search for a character in a string?](http://stackoverflow.com/questions/26115551/how-can-i-search-for-a-character-in-a-string) – Barmar Feb 06 '15 at 02:25
  • Probably use `std::getline` to read a line, then `find(",")` to see if it contains a comma. – Jerry Coffin Feb 06 '15 at 02:25
  • Your question doesn't seem to have anything to do with `getline()`. You just want to know how to search for a comma in the string, the fact that you got the string with `getline()` is hardly relevant. – Barmar Feb 06 '15 at 02:25

1 Answers1

1

Using getline and find, you can easily count the number

getline will iterate on each line of your file

find will look for the number of coma in the current line, if you add 1, this should give you the count of number

This assumes that your file is well formatted

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

int main () {
  string line;
  ifstream myfile ("example.txt");
  if (myfile.is_open())
  {
    int i = 1;
    while ( getline (myfile,line) )
    {
      size_t numberCount = std::count(line.begin(), line.end(), ',') + 1;
      cout << "Line "<< i << " has " << numberCount << " numbers"<<endl;
      i++;
    }
    myfile.close();
  }
  else cout << "Unable to open file"; 

  return 0;
}
Jérôme
  • 8,016
  • 4
  • 29
  • 35