Hello, for the program below i need to write a function (int str_to_int) which will convert the string of characters to integers and than another one (int calculate_sum) which will calculate sum of them.
This program is supposed to read from .txt file (which contains 5 numbers:
2341
23451
121
887
2301
5551
Can anybody help me, I have no idea where are to start.
Code:#include <iostream> using namespace std; int const STR_SIZE = 30; int const ARR_SIZE = 100; char const DELIMITER = '\n'; int readLine(char str[], int max, char delimiter); /* This function reads several lines of characters from standard input stream * Stops reading when it reads a delimiter characte (for example '\n'), * or when reaches the end of file, or...when the number of charaters read, * reaches to the limit (max number of charaters) * Adds a backslash zero as a string terminator to the end of string. * Returns -1 if reads the end of file otherwise returns 1. * Terminates the program if any error happens when reading characters. */ int str_to_int(const char digits[]); /* str represents an array of characters that contains digits terminated with * a '\0'. For example: it may contain digits[0] == '7', digits[1] == '5', * digits[2]== '3', and digit[3] == '\0'. * ‘\0’ is also know as c_string terminator. I is used in indicate the end of * the string. * This function should return an equivalent integer value for digits. * For the above example, it should return integer: 753. */ int calculate_sum(int int_number, int n); int readLine(char str[], int max, char delimiter) { char c; int i =0; do { cin.get(c); // a standard input function that reads characters if(!cin.eof() && cin.fail()){ cout << "\nReading from input stream failed..."; exit(1); } if(cin.eof()) return -1; if(i == max-1 || c == '\n' ) break; else str[i] = c; i++; } while(1); str[i] = '\0'; // put a backslash zero to the end of str. return 1; } int main(void) { char str[STR_SIZE]; int int_numbers [ARR_SIZE]; cout << "\nThis program reads numbers from a text file, using redirection "; cout << "\n input operator \'<\'on the command line." << endl; cout << "\nReading and echoing input ...." << endl; int i=0; // an infinite loop that will be terminated with a break statement while(1){ // read one line from the input stream if(readLine(str, STR_SIZE, DELIMITER) == -1) break; // display the string of characters on the screen cout << endl << str; //UNCOMMENT THE FOLLOWING LINE TO TEST THEIR FUNCTION; // int_number[i] = str_to_int(str); i++; } // UNCOMMENT THE FOLLOWING LINES TO TEST THEIR FUNCTION; // int total = calculate_sum(int_numbers, i ); // cout << "\n\nThe total of the numbers in the given file is: " << total; cout << "\nProgram Terminated. Bye..." << endl; return 0; }



LinkBack URL
About LinkBacks



