user566094
user566094

Reputation: 7

Formatting C-strings

The program is supposed to use a function that accepts a pointer to a C-string as an argument and capitalizes the first character of each sentence in the string. I'm having trouble with the output. This is my code:

#include "stdafx.h"
#include <cstring>
#include <iostream>

using namespace std;

void Capitalize(char *);

int _tmain(int argc, _TCHAR* argv[])
{
    char sentence[1000];


    cout << "Please enter a sentence: " << endl;
    cin.getline(sentence, 1000);

    char *sentencePtr = sentence;


    Capitalize(sentencePtr);

    cout << sentencePtr;

    cin.get();
    return 0;
}

void Capitalize(char *str){
    int count;

    for(count = 0; count < strlen(str); count++){

        if(str[count] = '.'){

            count += 2;

            toupper(str[count]);

        }



    }

}

Upvotes: 0

Views: 1076

Answers (5)

Gustavo Maciel
Gustavo Maciel

Reputation: 652

Looks like your comparison is wrong. Try changing

if(str[count] = '.')

to

if(str[count] == '.'){

remember -> = is a assignment operator == is a comparison operator

(I think your Capitalize func is wrong, but i dont know if its how you want it to be)

Upvotes: 0

Luchian Grigore
Luchian Grigore

Reputation: 258548

You have a typo here:

if(str[count] = '.')

should be:

if(str[count] == '.')

Also, str[count] = toupper(str[count]);

Upvotes: 0

David Schwartz
David Schwartz

Reputation: 182743

        toupper(str[count]);

This converts the character to upper case and then throws the result away. You want:

        str[count]=toupper(str[count]);

Also, this is an assignment:

    if(str[count] = '.'){

You want a comparison:

    if(str[count] == '.'){

Upvotes: 2

Matt Lacey
Matt Lacey

Reputation: 8255

You're using an assignment operator (=) not a comparison (==), you need to change:

if(str[count] = '.'){

To:

if(str[count] == '.'){

As others have indicated, your use of toupper isn't quite right either, as it returns the new value, it doesn't modify the orignal as it doesn't take a reference.

str[count] = toupper(str[count]);

Upvotes: 0

dreamlax
dreamlax

Reputation: 95315

That's a good go, but toupper returns the uppercase version of a character, it does not modify the argument that is provided. Try this:

 // note, you must use '==', not '='
 if(str[count] == '.')
 {
        count += 2;
        str[count] = toupper(str[count]);
 }

As an exercise, try and avoid using C-strings altogether, and see if you can do it using only the std::string class. Ultimately, you will realise that using std::string is much easier than using plain old C-strings.

Upvotes: 0

Related Questions