Hi all, I need some help on what is going on with my code. So, I have a file, called data, and it contains some unknown number of lines that I have to read all of them in, and output them with the first two characters of each word capitalized if they are alphabetic characters and use a function called process that takes one argument, a string and this function should not print anything out, but return a string which is the processed string.
This is what I have and it is printing out the line in capital letters instead of just printing out the first two characters of each word capitalized:
#include <iostream>
#include <string>
#include <fstream>
#include <sstream>
// capitalise the first two characters of each word (if they are alphabetic characters)
std::string process( std::string word ) // note: not a particularly great function name
{
// if the word has at least one char
if( !word.empty() ) word[0] = std::toupper( word[0] ) ; // capitalise the first char if alphabetic
// if the word has at least two chars
if( word.size() > 1 ) word[1] = std::toupper( word[1] ) ; // capitalise the second char if alphabetic
return word ; // return the processed string
}
// print out the line after capitalising the first two chars in each word
// note: we assume that words are sequences of characters delimited by a space
void process_line( const std::string& line )
{
// create an input string stream to read words from the line
// http://en.cppreference.com/w/cpp/io/basic_istringstream
std::istringstream stm(line) ;
std::string word ;
while( stm >> word ) // for each word read from the file
std::cout << process(word) << ' ' ; // print it out after capitalisation
std::cout << '\n' ; // finally print a new line
}
int main()
{
const std::string file_name = "/usr/share/doc/bc/README" ;
if( std::ifstream file{file_name} ) // if the file could be opened for input
{
std::string line ;
// process each line read from the file
while( std::getline( file, line ) ) process_line(line) ;
}
else std::cout << "could not open file for input\n" ;
}