Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading till the end of a line in C++

Tags:

c++

file

I have a text file like this :

Sting Another string 0 12 0 5 3 8
Sting Another string 8 13 2 0 6 11

And I want to count how many numbers are there. I think my best bet is to use while type cycle with a condition to end counting then another line starts but I do not know how to stop reading at the end of a line.

Thanks for your help in advance ;)

like image 807
Povylas Avatar asked Oct 24 '11 05:10

Povylas


1 Answers

Split your input stream into lines

std::string line;
while (std::getline(input, line))
{
  // process each line here
}

To split a line into words, use a stringstream:

std::istringstream linestream(line); // #include <sstream>
std::string word;
while (linestream >> word)
{
  // process word
}

You can repeat this for each word to decide whether it contains a number. Since you didn't specify whether your numbers are integer or non-integers, I assume int:

std::istringstream wordstream(word);
int number;
if (wordstream >> number)
{
  // process the number (count, store or whatever)
}

Disclaimer: This approach is not perfect. It will detect "numbers" at the beginning of words like 123abc, it will also allow an input format like string 123 string. Also this approach is not very efficient.

like image 103
René Richter Avatar answered Oct 14 '22 01:10

René Richter