Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Range-Based For Loops with Char Pointer String [duplicate]

I'm new to C++11, and quite frankly, I haven't used C++ in well over a year, so I'm a bit rusty to begin with. I'm doing some exercises from my old college text, and I've run into a problem while trying to iterate over a char pointer string (Ex: char * c = "a string";). I haven't been able to find anything helpful on Google. I'm so used to Java where the foreach loop can just iterate over any collection. I know how pointers work, but my long vacation from C++ has left me clueless about the syntax of actually using them. Can someone tell me why the following code (specifically, the convert() function) causes an error in compilation, in which it says "begin" and "end" were not declared in this scope?

Ex12_01_RomanType.h

#ifndef EX12_01_ROMANTYPE_H
#define EX12_01_ROMANTYPE_H

class RomanType {
  public:
    RomanType();
    RomanType(char * n);
    virtual ~RomanType();

    char * toString();
    int getValue();
  private:
    char * numeral;
    int decimal;

    void convert();
};

#endif // EX12_01_ROMANTYPE_H

Ex12_01_RomanType.cpp

#include "Ex12_01_RomanType.h"

RomanType::RomanType() {
  // Default Constructor
  numeral = "I";
  decimal = 0;
  convert();
}

RomanType::RomanType(char * n) {
  // Specific Constructor
  numeral = n;
  decimal = 0;
  convert();
}

RomanType::~RomanType() {
  delete numeral;
}

char * RomanType::toString() {
  return numeral;
}

int RomanType::getValue() {
  return decimal;
}

void RomanType::convert() {
  /* Iterates over each character in the numeral string and adds that
     character's value to the decimal value. This method should only
     be called once during the constructor. */
  for(char c : numeral) {
    if(c == 'M') decimal += 1000;
    else if(c == 'D') decimal += 500;
    else if(c == 'C') decimal += 100;
    else if(c == 'L') decimal += 50;
    else if(c == 'X') decimal += 10;
    else if(c == 'V') decimal += 5;
    else if(c == 'I') decimal += 1;
    else decimal += 0;
  }
}

Sorry if this question seems basic to some. Java has spoiled me.

like image 468
Darin Beaudreau Avatar asked Aug 02 '13 15:08

Darin Beaudreau


1 Answers

Range-based-for works on arrays, classes with member begin and end, or when there is an appropriate non-member begin and end.

You cant find the "end" of a c-style string (pointer to NUL-terminated char array) without walking all the way through it.

The simplest fix is just to use std::string, which will work with range-based-for.

(Edit: Now that I think of it, be careful even if you use a char array directly:

const char myString[] = "Hello";
for ( auto c : myString ) //...

because you will process all 6 members of the array, including the NUL-terminator. Although you can't do that here.)

like image 79
BoBTFish Avatar answered Oct 21 '22 10:10

BoBTFish