There are several ways to parse the integer value out of the string.
First, let's fix your loop:
int pos = 0;
while( std::getline(in, line) && pos < 100 )
{
int value = 0;
// Insert chosen parsing method here
arr[pos++] = value;
}
Here is a non-exhaustive list of common options:
Use std::strtol
// Will return 0 on error (indistinguishable from parsing actual 0)
value = std::strtol( line.c_str(), nullptr, 10 );
Use std::stoi
// Will throw exception on error
value = std::stoi( line );
Build a std::istringstream and read from it:
std::istringstream iss( line );
iss >> value;
if( !iss ) {
// Failed to parse value.
}
Use std::sscanf
if( 1 != std::sscanf( line.c_str(), "%d", &value ) )
{
// Failed to parse value.
}
Now, note the bounds-test on the loop checking pos < 100. This is because your array has a storage limit. Actually, you have also overridden the global one with a local one in Read_Save, thus hiding it with a smaller array that will be lost when the function finishes.
You can have an arbitrary-sized "array" (not actually an array) using other container types provided by the standard library. Useful ones that provide random access are std::vector and std::deque. Let's use the vector and change the definition of Read_Save to be a bit more useful:
std::vector<int> Read_Save( std::istream & in )
{
std::vector<int> values;
std::string line;
for( int line_number = 1; getline( in, line ); line_number++ )
{
try {
int value = std::stoi( line );
values.push_back( value );
}
catch( std::bad_alloc & e )
{
std::cerr << "Error (line " << line_number << "): Out of memory!" << std::endl;
throw e;
}
catch( std::exception & e)
{
std::cerr << "Error (line " << line_number << "): " << e.what() << std::endl;
}
}
return values;
}
And finally, the call becomes:
std::ifstream in( "file.txt" );
std::vector<int> values = Read_Save( in );
strcpywhile (in.peek() != EOF)will work, and good on you for not falling into the test for EOF before reading EOF trap, you may findwhile (getline(in, line, '\n'))better because it save you thepeekand catches more failure cases than just EOF.