Write a program that will read in a sentence of up to 100 characters and output the sentence with spacing corrected and with letters corrected for capitalization. In other words, int the output sentence all strings of two or more blanks should be compressed to a single blank. The sentence should start with an uppercase letter but should contain no other uppercase letters. Do not worry about proper names; if the first letter is changed to lowercase, that is acceptable. Treat a line break as if it were a blank space in the sense that a line break and any number of blanks are compressed to a single blank. Assume that the sentence ends with a period and contains no other periods.
Example input:
the Answer to life, the Universe, and everything IS 42.
should produce the following output:
The answer to life, the universe, and everything is 42.

here is the code I have so far.

#include <iostream>
#include <string>
#include <cctype>
using namespace std;

void swap(char& v1, char& v2);
//Interchanges the values of v1 and v2.

string remove(const string& s);
//Returns a copy of s but with extra whitespaces removed.

string makeUpper (const string& s);
//Returns a copy of s that has all lowercase
//characters changed to uppercase, with other characters unchanged.


int main()
{
    string str;
    cout << "Enter a sentence to be corrected\n"
         << "followed by pressing Return.\n";
    getline(cin, str);

    return 0;
}


void swap(char& v1, char& v2)
{
    char temp = v1;
    v1 = v2;
    v2 = temp;
}

string remove(const string& s)
{
    int start = 0;
    int end = s.length();
    string temp(s);

    {
        end--;
        swap(temp[start], temp[end]);
        start++;
    }

    return temp;
}

//Uses <cctype> and <string>
string makeUpper(const string& s)
{
    string temp(s);
    for (int i = 0; i < s.length(); i++)
        temp[i] = toupper(s[i]);

    return temp;
}

string removePunct(const string& s, const string& punct)
{
    string noPunct; //initialized to empty string
    int sLength = s.length();
    int punctLength = punct.length();
    for (int i = 0; i < sLength; i++)
    {
        string aChar = s.substr(i,1); //A one-character string
        int location = punct.find(aChar, 0);
        //Find location of successive charcters
        //of src in punct.

    if (location < 0 || location >= punctLength)
        noPunct = noPunct + aChar; //aChar is not in punct, so keep it
    }

    return noPunct;
}

Dani AI

Generated

Nice job getting started. The simplest way to meet the spec is a single pass over the input that normalizes whitespace and case as you go. As hinted, fix the compile errors first (use s.length() or s.size(), not s.length(1), and close blocks with } not ]). Also avoid modifying char* buffers; with C++ strings it is safer and clearer.

The workflow:

  • Read characters until the first period. Treat any whitespace (space, tab, newline) as a space.
  • Collapse runs of whitespace to a single space and trim leading/trailing space just before the period.
  • Lowercase everything, then uppercase the first alphabetic character.
  • Append the period back.

Here is a compact C++03 solution that works in VS 2008 and respects the 100-char limit:

#include <iostream>
#include <string>
#include <cctype>

std::string normalize_sentence(std::istream& in) {
    std::string out;
    out.reserve(100);
    bool inSpace = true;                 // collapse leading spaces
    int ch;
    size_t count = 0;
    while ((ch = in.get()) != EOF && ch != '.' && count < 100) {
        unsigned char c = static_cast<unsigned char>(ch);
        if (std::isspace(c)) {
            if (!inSpace) { out.push_back(' '); inSpace = true; }
        } else {
            out.push_back(static_cast<char>(c));
            inSpace = false;
        }
        ++count;
    }
    if (!out.empty() && out.back() == ' ') out.pop_back();  // trim before period
    for (size_t i = 0; i < out.size(); ++i)                 // lowercase all
        out[i] = static_cast<char>(std::tolower(static_cast<unsigned char>(out[i])));
    for (size_t i = 0; i < out.size(); ++i)                 // uppercase first letter
        if (std::isalpha(static_cast<unsigned char>(out[i]))){ 
            out[i] = static_cast<char>(std::toupper(static_cast<unsigned char>(out[i])));
            break;
        }
    out.push_back('.');                                     // ensure period
    return out;
}

int main() {
    std::cout << "Enter a sentence ending with a period:\n";
    std::string result = normalize_sentence(std::cin);
    std::cout << result << "\n";
}

Tip: always cast to unsigned char before std::tolower/std::toupper to avoid undefined behavior on non-ASCII bytes. and , drop this into your project and test with extra spaces and newlines; it should match the required output exactly.

Recommended Answers

All 4 Replies

Well, your main block only reads in a line -- where in particular are you looking for help/where are you stuck?

Well, your main block only reads in a line -- where in particular are you looking for help/where are you stuck?

Ok so I did some more work on the code but I am now getting errors could use some input here:

#include <iostream>
#include <string>
#include <cctype>
using namespace std;

char * RemoveSpaces(char * source);

string makeUpper (const string& s);
//Returns a copy of s that has all lowercase
//characters changed to uppercase, with other characters unchanged.

string makeLower (const string& s);


int main()
{
    string str;
    cout << "Enter a sentence to be corrected\n"
         << "followed by pressing Return.\n";
    getline(cin, str);

    return 0;
}

char * RemoveSpaces(char * source)
{
    char * dest, * ret = dest = source;
    while( *(isspace(*source) ? dest : dest++) = *source++ );

	return ret;
}


//Uses <cctype> and <string>
string makeUpper(const string& s)
{
    string temp(s);
    char c = toupper('a');
    cout << c;

    for (int i = 0; i < s.length(1); i++)
        temp[i] = toupper(s[i]);

    return temp;
}

string makeLower(const string& s)
{
    string temp(s);
    char c = tolower('A');
    cout << c;

    for (int i = 1; i < s.length(); i++)
        temp[i] = tolower(s[i]);

    return temp;

]

these are the errors I'm getting now:
C:\Users\Karen\Documents\CPSC 122\Lesson Exercises\chap9\C9Q1.cpp: In function `std::string makeLower(const std::string&)':
C:\Users\Karen\Documents\CPSC 122\Lesson Exercises\chap9\C9Q1.cpp:62: error: expected primary-expression before ']' token
C:\Users\Karen\Documents\CPSC 122\Lesson Exercises\chap9\C9Q1.cpp:62: error: expected `;' before ']' token
C:\Users\Karen\Documents\CPSC 122\Lesson Exercises\chap9\C9Q1.cpp:62: error: expected `}' at end of input
Process terminated with status 1 (0 minutes, 1 seconds)
4 errors, 0 warnings

Well, those 3 errors are generated because you've "ended" makeLower with ']' instead of '}'. Also, you may want to look at "s.length(1)" from makeUpper(...)

I'm having the same problem as this previous user, doing the same program. I know it's rhudementary, but I just switched from math to programming and am going for Dr., and am 50+. I will put in the 100 hours per week to get geek, but at this point am freek. Please help. Using VS 2008, C++. :)

Write a program that will read in a sentence of up to 100 characters and output the sentence with spacing corrected and with letters corrected for capitalization. In other words, int the output sentence all strings of two or more blanks should be compressed to a single blank. The sentence should start with an uppercase letter but should contain no other uppercase letters. Do not worry about proper names; if the first letter is changed to lowercase, that is acceptable. Treat a line break as if it were a blank space in the sense that a line break and any number of blanks are compressed to a single blank. Assume that the sentence ends with a period and contains no other periods.
Example input:
the Answer to life, the Universe, and everything IS 42.
should produce the following output:
The answer to life, the universe, and everything is 42.

here is the code I have so far.

C++ Syntax (Toggle Plain Text)

#include <iostream>#include <string>#include <cctype>using namespace std; void swap(char& v1, char& v2);//Interchanges the values of v1 and v2. string remove(const string& s);//Returns a copy of s but with extra whitespaces removed. string makeUpper (const string& s);//Returns a copy of s that has all lowercase//characters changed to uppercase, with other characters unchanged.  int main(){    string str;    cout << "Enter a sentence to be corrected\n"         << "followed by pressing Return.\n";    getline(cin, str);     return 0;}  void swap(char& v1, char& v2){    char temp = v1;    v1 = v2;    v2 = temp;} string remove(const string& s){    int start = 0;    int end = s.length();    string temp(s);     {        end--;        swap(temp[start], temp[end]);        start++;    }     return temp;} //Uses <cctype> and <string>string makeUpper(const string& s){    string temp(s);    for (int i = 0; i < s.length(); i++)        temp[i] = toupper(s[i]);     return temp;} string removePunct(const string& s, const string& punct){    string noPunct; //initialized to empty string    int sLength = s.length();    int punctLength = punct.length();    for (int i = 0; i < sLength; i++)    {        string aChar = s.substr(i,1); //A one-character string        int location = punct.find(aChar, 0);        //Find location of successive charcters        //of src in punct.     if (location < 0 || location >= punctLength)        noPunct = noPunct + aChar; //aChar is not in punct, so keep it    }     return noPunct;}#include <iostream>
#include <string>
#include <cctype>
using namespace std;

void swap(char& v1, char& v2);
//Interchanges the values of v1 and v2.

string remove(const string& s);
//Returns a copy of s but with extra whitespaces removed.

string makeUpper (const string& s);
//Returns a copy of s that has all lowercase
//characters changed to uppercase, with other characters unchanged.


int main()
{
    string str;
    cout << "Enter a sentence to be corrected\n"
         << "followed by pressing Return.\n";
    getline(cin, str);

    return 0;
}


void swap(char& v1, char& v2)
{
    char temp = v1;
    v1 = v2;
    v2 = temp;
}

string remove(const string& s)
{
    int start = 0;
    int end = s.length();
    string temp(s);

    {
        end--;
        swap(temp[start], temp[end]);
        start++;
    }

    return temp;
}

//Uses <cctype> and <string>
string makeUpper(const string& s)
{
    string temp(s);
    for (int i = 0; i < s.length(); i++)
        temp[i] = toupper(s[i]);

    return temp;
}

string removePunct(const string& s, const string& punct)
{
    string noPunct; //initialized to empty string
    int sLength = s.length();
    int punctLength = punct.length();
    for (int i = 0; i < sLength; i++)
    {
        string aChar = s.substr(i,1); //A one-character string
        int location = punct.find(aChar, 0);
        //Find location of successive charcters
        //of src in punct.

    if (location < 0 || location >= punctLength)
        noPunct = noPunct + aChar; //aChar is not in punct, so keep it
    }

    return noPunct;
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.