How to read an integer group in the file in C

I have a text file, each line contains one or more integers, separated by spaces. How can I read this in C in an elegant way? If I don’t care about the line, I can use cin>>, but the important thing is which line is an integer.

Input example:

1213 153 15 155
84 866 89 48
12
12 12 58
12

It depends on whether you want to line by line or a full set. Convert the entire file to a vector of integers:

int main() {< br /> std::vector v( std::istream_iterator(std::cin), 
std::istream_iterator() );
}

If you want to process per line:

int main()
{
std::string line;
std::vector< std::vector> all_integers;
while (getline( std::cin, line)) {
std::istringstream is( line );
all_integers .push_back(
std::vector( std::istream_iterator(is),
std::istream_iterator()) );
}
}

I have a text file, each line contains one or more integers, separated by spaces. How can I read this in C in an elegant way? If I don’t care about the line, I can use cin>>, but the important thing is which line is an integer.

Input example:

1213 153 15 155
84 866 89 48
12
12 12 58
12

It depends on you Do you want to go line by line or a full set. Convert the entire file to a vector of integers:

int main() {
std::vector v( std::istream_iterator(std::cin),
std::istream_iterator() );
}

If you want to process per line :

int main()
{
std::string line;
std::vector< std::vector > all_integers;
while (getline( std::cin, line)) {
std::istringstream is( line );
all_integers.push_back(
std::vector< int>( std::istream_iterator(is),
std::istream_iterator()) );
}
}

Leave a Comment

Your email address will not be published.