#include <iostream>
#include <string>
#include <vector>
#include <cctype>
#include <fstream>
// get each digit in the line of text into a vector
// (ignore non-digit characters if any are present)
std::vector<int> get_digits( const std::string& line )
{
std::vector<int> result ;
for( char c : line ) // for each char in the line
{
// if it is a decimal digit,
// "the behavior of std::isdigit is undefined if the argument's value is
// neither representable as unsigned char nor equal to EOF
// To use std::isdigit safely with plain chars,
// the argument should first be converted to unsigned char"
// see: https://en.cppreference.com/w/cpp/string/byte/isdigitif( std::isdigit( static_cast<unsignedchar>(c) ) )
result.push_back( c - '0' ) ; // add the integer value to the vector
// note that '7' - '0' == 7 etc.
// else there is an error: it is a badly formed line
}
return result ;
}
int main()
{
const std::string input_file_name = "numbers.txt" ;
if( std::ifstream file { input_file_name } ) // if the file was opened for input
{
std::string line ;
while( std::getline( file, line ) ) // for each line in the file
{
std::cout << "line: " << line << '\n' ; // print out the line
constauto digits = get_digits(line) ; // get the digits in the line
std::cout << "there are " << digits.size() << " digits in the line.\nthey are: " ;
// print out the digits one by one
for( int d : digits ) std::cout << d << ' ' ;
std::cout << '\n' ;
// TO DO: do something interesting with those digits
}
}
else
std::cerr << "error: failed to open input file '" << input_file_name << "'\n" ;
}
@gktrktrn7635
A simple extension of your program and using @lastchance conversion from char to int and std::list instead of writing your own node list you get the following: