How do i use the function isspace to take sentences read into an array and make multiple spaces only one space between words? Use an if statement?

if (isspace(aChar) )
cout << aChar;

else (

Not sure what I need here.

Dani AI

Generated

Brief summary and a simple, robust approach that ties the earlier suggestions together: use a std::string, extract words with a stringstream (this collapses any run of whitespace to single spaces and trims ends), lowercase the whole result, then uppercase the first alphabetic character. This combines 's "track output" idea, 's copy-with-two-indices intent, and the std::string/trim recommendation from and — but avoids manual index juggling and works cleanly for tabs/newlines as well.

Example implementation (C++11+). It reads a full line, collapses internal whitespace, lowercases everything, and capitalizes the first letter it finds:

#include <iostream>
#include <sstream>
#include <string>
#include <algorithm>
#include <cctype>

std::string normalize(std::string s) {
    std::istringstream iss(s);
    std::ostringstream oss;
    std::string word;
    bool first = true;
    while (iss >> word) {
        if (!first) oss << ' ';
        oss << word;
        first = false;
    }
    s = oss.str();
    if (s.empty()) return s;
    std::transform(s.begin(), s.end(), s.begin(),
        [](unsigned char ch)->char { return static_cast<char>(std::tolower(ch)); });
    for (char &c : s) {
        if (std::isalpha(static_cast<unsigned char>(c))) {
            c = static_cast<char>(std::toupper(static_cast<unsigned char>(c)));
            break;
        }
    }
    return s;
}

int main() {
    std::string line;
    std::getline(std::cin, line);
    std::cout << normalize(line) << '\n';
}

Quick notes and pitfalls:

  • Always cast to unsigned char before calling std::tolower/std::toupper/std::isalpha to avoid undefined behavior on negative char values.
  • std::istringstream >> word treats any whitespace (space, tab, newline) as delimiters — good for collapsing but not if you must preserve newlines/tabs.
  • This works for ASCII/locale-aware single-byte text. UTF-8 or other multi-byte encodings require a Unicode-aware library.
  • Prefer std::getline/std::string over raw char arrays; avoid platform hacks like system("PAUSE") (see ).

Recommended Answers

All 11 Replies

Are you reading the sentence all at once, or word by word?

im trying to take user input in the form of a sentence putting it in an array and then print out changes: Capitalize the first letter, then the rest of the letters are lower case. If there are multiple spaces, make them only one. Maybe I don't have to use isspace?

const int SIZE = 100;
int main()
{
    char sentence[SIZE];
cout << "Please enter a short sentence: " << endl;
cin.getline(sentence, SIZE);

for (int i = 1; i < 100; i++)
        sentence[i] = tolower(sentence[i]);
for (int i = 0; i < 1; i++)
        sentence[i] = toupper(sentence[i]);    
//if (isspace(sentence))
    cout << sentence;
    
return 0;
system("PAUSE");
}

Output the characters in a loop. Keep track of the previous character you've output. If it was a space, then if the current character is a space, don't output it.

Not sure how to output using a loop? Can you show me please?

Maybe I don't have to use isspace?

Yeah. You dont. Consider the use of std::string and std:stringstream.

Anyway this should do for now.

const int SIZE = 100;
int main()
{
   /*
    *   Remember to initialize char arrays
    */
    char sentence[SIZE] = "";
    std::cout << "Please enter a short sentence: " << std::endl;
    std::cin.getline(sentence, SIZE);

   /*
    *   Remove leading spaces
    */
    int i = 0;
    while( i < SIZE && isspace( sentence[i] ))
    {
        i++;
    };
   /*
    *   Check if the array has finished traversing
    */
    if ( i == SIZE )
        return 0;
   /*
    *   Capitalize the first non-space character
    */
    std::cout << (char)toupper(sentence[i++]);
   /*
    *   Start after the leading spaces
    *   Note that this will leave a trailing space,
    *   but that wont be seen.
    */
    for ( ; i < SIZE; )
    {
        std::cout << (char)tolower(sentence[i]);
        if (isspace( sentence[i] ))
        {
            do
            {
                i++;
            }
            while( i < SIZE && isspace( sentence[i] ) );
        }
        else
        {
            i++;
        }
    }
    return 0;
}

Not sure how to output using a loop? Can you show me please?

Simple. Using your code, and formatting it correctly with proper indentation -- please learn this. As your programs grow, they will become unreadable without proper formatting:

const int SIZE = 100;
int main()
{
    char sentence[SIZE];
    cout << "Please enter a short sentence: " << endl;
    cin.getline(sentence, SIZE);

    for (int i = 1; i < 100; i++)
    {    
//      sentence[i] = tolower(sentence[i]);
        cout << tolower(sentence[i]);   // output
    }
    for (int i = 0; i < 1; i++)
    {
//      sentence[i] = toupper(sentence[i]);    
        cout << toupper(sentence[i]);    // output
    }
//  return 0;        // wrong place 

//  system("PAUSE");  // Yech!!!!  Don't use this
    getchar();         // instead...

    return 0;        // right place 
}

Here is one that removes the trailing spaces too.

const int SIZE = 100;
int main()
{
   /*
    *   Remember to initialize char arrays
    */
    char sentence[SIZE] = "";
    std::cout << "Please enter a short sentence: " << std::endl;
    std::cin.getline(sentence, SIZE);
    int len = strlen( sentence );
   /*
    *   Remove trailing spaces
    */
    int i = len -1;
    while ( i >= 0 && isspace( sentence[i] ) )
    {
        i--;
    }
   /*
    *   Check if the array has finished traversing
    */
    if ( i < 0 )
    {
        return 0;
    }
    /*
     * Terminate the sentence before the trailing spaces and
     * update the new length
     */
    sentence[ i + 1 ] = 0;
    len = strlen( sentence );
   /*
    *   Remove leading spaces
    */
    i = 0;
    while( i < len && isspace( sentence[i] ))
    {
        i++;
    };
   /*
    *   Check if the array has finished traversing
    */
    if ( i == len )
        return 0;
   /*
    *   Capitalize the first non-space character
    */
    std::cout << (char)toupper(sentence[i++]);
   /*
    *   Start after the leading spaces
    */
    for ( ; i < len; )
    {
        std::cout << (char)tolower(sentence[i]);
        if (isspace( sentence[i] ))
        {
            do
            {
                i++;
            }
            while( i < len && isspace( sentence[i] ) );
        }
        else
        {
            i++;
        }
    }
    return 0;
}

If you use C++ strings your life would be much simpler coz then you can do something like:

#include <string> 
 
const std::string whiteSpaces( " \f\n\r\t\v" ); 
 
void trimRight( std::string& str, 
       const std::string& trimChars = whiteSpaces ) 
 { 
    std::string::size_type pos = str.find_last_not_of( trimChars ); 
    str.erase( pos + 1 ); 
 
} 
 

void trimLeft( std::string& str, 
       const std::string& trimChars = whiteSpaces ) 
 { 
    std::string::size_type pos = str.find_first_not_of( trimChars ); 
    str.erase( 0, pos ); 
 } 
 

void trim( std::string& str, const std::string& trimChars = whiteSpaces ) 
 { 
    trimRight( str, trimChars ); 
    trimLeft( str, trimChars ); 
 }

How do I remove extra spaces in between?

How do I remove extra spaces in between?

In between words, lines, sentences, paragraphs, or characters? Please be explicit. Only you know what you want and we can't read minds if you're not in the room with us.

U can use a loop like this in WaltP's code..

char newsentence[100];
for (int i = 0,j=0; i < 100;)
    {    
        if (sentence[i] == ' ')
       {
           newsentence[j++]=sentence[i];  
           while(sentence[i]==' ') 
               i++;
        }
        else
           newsentence[j++]=sentence[i++];  
     } 
 
newsentence[j]='/0';
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.