开发者

array of C++ string types

开发者 https://www.devze.com 2023-01-15 22:35 出处:网络
These are my variables: const int sizeOf开发者_如何学GoLicToCheckFor = 3; string licNameToCheckFor[ sizeOfLicToCheckFor ] = { \"PROF\", \"PERS\", \"PREM\" };

These are my variables:

    const int sizeOf开发者_如何学GoLicToCheckFor = 3;
string licNameToCheckFor[ sizeOfLicToCheckFor ] = { "PROF", "PERS", "PREM" };

when I run my program licNameToCheckFor is only initialized with "PROF" and nothing else. What am I doing wrong?


How are you checking if it was initialized properly? Most probably you are doing that wrong because code is absolutely correct:

#include <string>
#include <iostream>

using namespace std;

int
main ()
{
    const int sizeOfLicToCheckFor = 3;
    string licNameToCheckFor[ sizeOfLicToCheckFor ] = { "PROF", "PERS", "PREM" };
    for (int i = 0; i < sizeOfLicToCheckFor; ++i)
    {
        cout << licNameToCheckFor[i] << endl;
    }
}

The output:

$ g++ -o test ./test.cpp
$ ./test 
PROF
PERS
PREM

You can also simplify your code by not specifying number of strings in array, like this:

string licNameToCheckFor [] = { "PROF", "PERS", "PREM" };


Works for me.

Why do you think it is not working?

#include <string>
#include <iostream>

const int sizeOfLicToCheckFor = 3;
std::string licNameToCheckFor[ sizeOfLicToCheckFor ] = { "PROF", "PERS", "PREM" };

int main(int argc, char** argv)
{
    std::cout << licNameToCheckFor[0] << " ";
    std::cout << licNameToCheckFor[1] << " ";
    std::cout << licNameToCheckFor[2] << " ";
}

> vi t.cpp
> g++ t.cpp
> ./a.exe
PROF PERS PREM >
0

精彩评论

暂无评论...
验证码 换一张
取 消