Hello! I have a task to prompt user to enter file path, read it into array up to 1024 and discard single characters. I now that it is somehow connected to the ASCII and while i can think of how to discard symbols what to do with single letters?
#include <iostream>
#include <string>
#include <fstream>
#include<iomanip>
usingnamespace std;
void readTxt(string[]);
constint SIZE = 1024;
int main()
{
string txtArr[SIZE];
readTxt(txtArr);
getchar();
system("pause");
return 0;
}
void readTxt(string txtArr[])
{
string fileName;
ifstream inFile;
cout << "Enter Full File Path : "; //Will that work for location also?
getline(cin, fileName);
inFile.open(fileName.c_str());
while (inFile.fail()) //Check for mistakes in opening file
{
cout << "Error! Please enter the file name: ";
cin >> fileName;
inFile.clear();
inFile.open(fileName.c_str());
}
if (inFile) //If the file opened successfully, process it
{
int count = 1;
while (count < SIZE && inFile >> txtArr[count])
//I would enter for loop here to discard single characters
count++;
}
inFile.close();
}
#include <iostream>
#include <string>
#include <fstream>
#include <iomanip>
// read white space separated tokens from the input stream into the array
// ignore tokens which are single characters
// return the number of tokens read
std::size_t read_text( std::string arr[], std::size_t arr_sz, std::istream& stm )
{
std::size_t n = 0 ;
while( n < arr_sz && stm >> arr[n] )
{
// if the string contains more than a single character
if( arr[n].size() > 1 ) ++n ; // increment the count of tokens read
}
return n ;
}
// read white space separated tokens (of 2+ characters) from the file into the array
// return the number of tokens read
std::size_t read_text( std::string arr[], std::size_t arr_sz, std::string file_name )
{
std::ifstream file(file_name) ;
return read_text( arr, arr_sz, file ) ;
}
std::string get_input_file_name()
{
std::string file_name ;
std::cout << "input file? ";
std::getline( std::cin, file_name );
if( std::ifstream(file_name).is_open() ) return file_name ;
std::cout << "could not open '" << file_name << "' for input. try again\n" ;
return get_input_file_name() ; // try again
}
int main()
{
constint SIZE = 1024;
std::string txt_arr[SIZE];
constauto n_read = read_text( txt_arr, SIZE, get_input_file_name() ) ;
// for each token that was read from the file
for( std::size_t i = 0 ; i < n_read ; ++i )
{
// do whatever. for example, print it out
std::cout << i+1 << ". '" << txt_arr[i] << "'\n" ; // print it out
}
}