Ad

How To Use Commas To Split Chars In A Loop?

- 1 answer

I'm writing a program in c++ and I'm trying to separate letters like this: "A,B,C"

But it comes out like this, and I don't know why: ",A,B,C".

Help?

My code is below:

#include <iostream>

#include <ctype.h>

using namespace std;


int main()

{
    
    
    char startChar='Z';
    
    char stopChar='A';
    
    while (startChar>stopChar)
        
    {
        
        cin >> startChar;
        
        startChar = toupper(startChar);
        
        
        cin >> stopChar;
        
        stopChar=toupper(stopChar);
        
    }
    
    for (char chLoop=startChar; chLoop<=stopChar; chLoop++)
        
    {
        if (stopChar > startChar)
            cout << ",";
        
        
        cout <<chLoop;
    }
    
}

thanks!

Ad

Answer

When stopChar is C and startChar is A, this condition will be true and therefore a , will be printed in every iteration of the loop (including the first):

if (stopChar > startChar)
    cout << ",";

You can fix it by changing it to:

if (chLoop != startChar)
    std::cout << ',';

That is, only if chLoop is notstartChar, print a ,.

Another option that doesn't require an if at all:

std::cout << startChar;         // print the first char before the loop
for (char chLoop = startChar + 1; chLoop <= stopChar; chLoop++) {
    std::cout << ',' << chLoop; // now print the , unconditionally
}
Ad
source: stackoverflow.com
Ad