-2

I've recently started learning c++ after 5 years with python and am struggling quite a bit when it comes to loops. the whole for(;;) business.

in python i was used to:

for x in y:
    print(x)

> x
> y
> z

however in c++ i seem to need two semi-colons like

for(;;)

what i would like to do is print the paths of my directories given in the below code. Thank you for your time!

#include <windows.h>
#include <string>
#include <iostream>

#pragma comment(lib, "user32.lib")

using namespace std;


HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);




// -- main
int main(void) {
    // -- console
    SetConsoleTextAttribute(hConsole, 12);
    
    // -- paths
    string ScanDir[2] = {"C:/Users/Stephen/Downloads/", "C:/Users/Stephen/Documents/"};
    
    // -- loops
    for (int i = 0; i < ScanDir->length(); ++i) {
        string ss = ScanDir[i];
        cout << ss.c_str() << "\n";
    }


    return 0;
}

here is the error:

error screenshot

RedKabin
  • 31
  • 3
  • 2
    `ScanDir->length();` -- What did you expect this to do? Also don't use `Python` or any other computer language as a model in writing C++ code. C++ is a different language with different rules, different syntax, different idioms. – PaulMcKenzie Jul 21 '20 at 17:48

2 Answers2

4

In C++ arrays are not objects in the OOP sense and do not have methods. They are just a dumb block of memory.

ScanDir->length()

is not getting the length of the array. Instread ScanDir is decaying to a pointer to the first string in the array and length is being called on this string. As a result

for (int i = 0; i < ScanDir->length(); ++i)

iterates length of the first string times, not length of the array, and shoots off the end of the array and into the unknown. This invokes Undefined Behaviour which in this case lead to a crash.

The smart thing to do is use a Range-based for loop

for (const auto & dir: ScanDir) {
    cout << dir.c_str() << "\n";
}

which figures out the dimensions for you. Some additional reading on the const auto & bit: What is the correct way of using C++11's range-based for?

You can also use

for (int i = 0; i < std::size(ScanDir); ++i) 

if compiling to C++ 17 or better or replace the magic number 2 in

string ScanDir[2] = {"C:/Users/Stephen/Downloads/", "C:/Users/Stephen/Documents/"};

with a constant that can be used wherever the size of the array is required.

Another alternative is replace the array with a smarter container like std::array

std::array<std::string, 2> ScanDir = {"C:/Users/Stephen/Downloads/", "C:/Users/Stephen/Documents/"};

which has a size method.

user4581301
  • 33,082
  • 7
  • 33
  • 54
0

ScanDir->length() is the length of your strings which is notably greater than 2. You can either use 2 as upper loop boundary or sizeof(ScanDir) / sizeof(ScanDir[0]), or type the loop itself as for(auto const &ss: ScanDir) count << ss.c_str() << '\n';.

bipll
  • 11,747
  • 1
  • 18
  • 32