0

Would someone kindly steer me in the proper direction with the following code I have written. Basically I'm trying to have every other character in a string be printed in an uppercase letter, all while not taking spaces or other non alpha characters into consideration.

example: string input = "thanks for the add" should print as "ThAnKs FoR tHe AdD"

int main (void) 
{
    char* input = GetString();
    if (input == NULL)
        return 1;
    for (int i = 0, x = strlen(input); i < x; i+=2)
        input [i] = toupper(input[i]);
    printf("%s\n", input);
    return 0;
}

note: I'm new to computer science and am currently taking CS50x through edx.org

user2153167
  • 33
  • 1
  • 2
  • 4

2 Answers2

1

Just use isalpha to ignore other kinds of characters:

#include <string.h>
#include <stdio.h>
#include <ctype.h>
int main (void) 
{
    char input[] = "thanks for the add";
    int  alpha_count = 0;
    for (int i = 0, x = strlen(input); i < x; i++) {
      if (isalpha(input[i])) {
        if (alpha_count++ % 2 == 0 ) 
          input [i] = toupper(input[i]);
      }   
    }   
    printf("%s\n", input);
    return 0;
}
perreal
  • 94,503
  • 21
  • 155
  • 181
  • Why is it necessary to call `isalpha`? If I remember correctly, the `toupper` function only modifies the character if it can be converted to uppercase (i.e., if it is an alphabetic character). Otherwise, it leaves it unmodified. – Cody Gray - on strike Mar 19 '13 at 03:31
  • Since the OP wants to alternate between uc/lc on alpa characters the if statement guards the counter. Otherwise a space also triggers the alternation counter. – perreal Mar 19 '13 at 03:33
  • thank you. I've spent more time on this than I care to admit. The use of the modulo is what I was missing. – user2153167 Mar 19 '13 at 05:24
-1
#include <iostream>
using namespace std;

int main()
{
    char st[] = "thanks for the add";
    for(int i=0; i<strlen(st); i++)
        st[i++]=toupper(st[i]);
    cout<<st<<endl;
}
  • Thank you for this code snippet, which might provide some limited, immediate help. A [proper explanation](https://meta.stackexchange.com/q/114762/349538) would greatly improve its long-term value by showing why this is a good solution to the problem and would make it more useful to future readers with other, similar questions. Please [edit] your answer to add some explanation, including the assumptions you’ve made. – Donald Duck Dec 13 '17 at 22:50