Search code examples
htmlc++fstreamcinspaces

How can I insert text WITH SPACES into a text document in C++ using cin?


I am very new to programming and I am trying to write a program in C++ that will convert text inputted by the user into HTML code and output that code onto a text file. I have already written the basic program and it works great. The only problem I am having is being able to input spaces in between words. For example, if you were to type into the program "HELLO WORLD", it would only display "HELLO" on the text file. I understand what the problem is, cin will read the text and stop at the whitespace, but I am trying to find out if there is any way around this? Any advice would be greatly appreciated, thank you.

The code I have written:

#include <iostream>
#include <cstdlib>
#include <fstream>
#include <iomanip>
#include <string.h>

using namespace std;

int main()
{
    ifstream( inputFile );
    ofstream( outputFile );
    char title[500];
    char heading[500];
    char color[10];
    char body[5000];

    outputFile.open("html.txt");

    cout << "Please enter a title: ";
    cin >> title;
    cout << "Please enter a heading: ";
    cin >> heading;
    cout << "What color would you like your heading to be? ";
    cin >> color;
    cout << "Please enter the body: ";
    cin >> body;

    outputFile << "<!doctype html> " << "\n" << "<html> " << "\n" << "<head> " << "<title> " << title << " " << "</title> " << "</head>" << "\n"
           << "<body> " << "\n" << "<h1> " << "<center> " << "<font color=\"" << color << "\"> " << heading << " " << "</font> " << "</center> " << "</h1> " << "\n"
           << body << " " << "\n" << "</body> " << "\n" << "</html> " << "\n";


    outputFile.close();

    system("PAUSE");
    return 0;

}

Solution

  • Here in your code you want to read the whole line entered, as far I understood your question well

    cout << "Please enter the body: ";
    std::getline(cin,body);
    

    Instead of declaring body as a plain char array (char body[5000];), you have to use a std::string instead:

    std::string body;
    

    Thus you get rid of bothering with estimating and reserving the maximum possible input length you could get.

    NOTE:
    The above sample just enables you to input a single line of HTML text, if you wan't to have multiline input, you either need to chose a different line delimiter (than the default '\n'), or accumulate subsequent inputs to body until e.g. an empty line or some other appropriate end marker is entered:

    std::string body;
    cout << "Please enter the body (stop entering a blank line): ";
    
    std string line;
    std::cin.clear(); // Get rid of all previous input state
    do {
        std::getline(cin,line);
        if(line.empty()) {
            break; // Stop the input loop
        } 
        else {
            body += line + "\n"; // accumulate the entered input to 'body'
        }
    } while(1);