[EASY] Programming Challenge 09-14-2013, 05:48 PM
#1
Hello members of Sinisterly. I've got an easy programming challenge for those of you who may be now learning to program. If experienced programmers wish to partake, they can as well.
Prerequisites
Problem
Write a program that will accept a file path through user input (e.g. filename.txt), open that file and count the total number of lines and characters in that file. These values should be returned to the user. If the file does not exist, the user should be informed of this and given another opportunity to provide a valid file path.
Solution
If you can't figure out how to do this, you can refer to my solution. It may be a tad bit overcomplicated for this particular problem, but you'll get the idea.
C++
http://pastebin.com/yiwvZjyd
Please provide the code you used to solve the problem via PM or between spoiler tags in a reply to this thread. If you solved it in another language, I can add your solution to the list.
Prerequisites
- Basic programming knowledge (variables, control structures)
- Understanding of basic file I/O in your desired programming language
Problem
Write a program that will accept a file path through user input (e.g. filename.txt), open that file and count the total number of lines and characters in that file. These values should be returned to the user. If the file does not exist, the user should be informed of this and given another opportunity to provide a valid file path.
Solution
If you can't figure out how to do this, you can refer to my solution. It may be a tad bit overcomplicated for this particular problem, but you'll get the idea.
Spoiler:
C++
Spoiler:
Code:
/*
* AUTHOR: Aristotle
* LANGUAGE: C++
* DESCRIPTION: This program will open a file, count the number of lines and characters,
* and then return the result to the user.
*/
#include <iostream>
#include <fstream>
#include <string>
int main(){
std::ifstream inputFile(NULL);
std::string fileName,line;
int lineCount=0,charCount=0;
while (!inputFile){
std::cout << "Enter file name in the format 'filename.extension' (e.g. hello.txt).\n";
std::cout << "File name: ";
std::cin >> fileName;
inputFile.open(fileName.c_str());
if (!inputFile){
std::cout << "File does not exist.\n";
inputFile.close();
}
}
std::cout << "File located. \nReading number of lines and characters...\n";
while(std::getline(inputFile, line)){
lineCount++;
charCount += line.length();
}
std::cout << "Total line count is " << lineCount << ".\n";
std::cout << "Total character count is " << charCount << ".\n";
return 0;
}Please provide the code you used to solve the problem via PM or between spoiler tags in a reply to this thread. If you solved it in another language, I can add your solution to the list.
![[+]](https://sinister.ly/images/modern/collapse_collapsed.png)










![[Image: 7ajmN5P.jpg]](https://i.imgur.com/7ajmN5P.jpg)






