Char Fields [ ]

Hi guys, I was looking for some tutorial or topic on google, but i didn't find it.

I need some function or something to determine how many fields are used,
for example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <iostream>

int main(){
  int NumberOfFields;
  wchar_t ch[30];//or char ch[30];

    //1234 fields of 30
  ch="abcd";

  NumberOfFields=SomeFunction(ch);

  cout<<"Number Of Fields: "<<ch;

  return 0;
}



   Number of fields: 4 //of 30

   


Can somebody help me ?
Last edited on
To determing the length of a char or wchar_t array you can use either strlen function from <cstring> or wcslen function from <cwchar>.
Also array in C/C++ has no the assignment operator. So you can not use

ch="abcd";

you should use either strcpy or wcscpy to copy a string literal to a character array.
Last edited on
If you're using C++ strings it's easy:

1
2
3
4
5
6
7
8
9
10
11
12
13
#include <string>
#include <iostream>

int main() {
  int NumberOfFields;
  std::wstring ch = "abcd";

  NumberOfFields=ch.size();

  cout<<"Number Of Fields: "<<NumberOfFields;

  return 0;
}


If you really want to use character arrays, look for the terminating character. Whenever you use double-quotes in C++, there is a hidden character at the end '\0';

So in your case:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>

int SomeFunction(wchar_t* ChArray)
{
  int i;
  for (i = 0; i < 30; ++i)
    if (ChArray[i] == '\0')
      return i;
  return -1; // Error code
}

int main(){
  int NumberOfFields;
  wchar_t ch[30] = "abcd";//or char ch[30];

  NumberOfFields=SomeFunction(ch);

  cout<<"Number Of Fields: "<<ch;

  return 0;
}
Last edited on
Thanks guys it was useful :)
Last edited on
Topic archived. No new replies allowed.