C-String Help

Hello. I need to write a program that prints the length of a string; however, I cannot use the <string> or <string.h> libraries. The directions are to: 1) Write a StringLength () function 2) Declare and initialize the string 3) Pass the string to StringLength () and 3) Print the length of a string. This is the code I have, but I keep getting the error message: "24|error: invalid conversion from 'char' to 'std::basic_istream<char>::char_type* {aka char*}' [-fpermissive]|" on the following line: "cin.getline(x, 199);" I have no idea what I am doing wrong. Thank you for any help!

#include <iostream>
#include <cstring>

using namespace std;

char StringLength (char x); //function definition
char LENGTH = 199;

int main()
{
char x;
char LENGTH = StringLength (x); //function call

cout << "Enter a string: ";
cin.getline(x, 199);

cout << "Total string length: " << LENGTH << endl;


return 0;
}
int StringLength (char *x){

int len;
for(len = 0; x[len]!='\0'; ++len);
return(len);

}
Last edited on
Your problem (for both of you) is that you are passing a char, rather than a pointer to char (C-String). That is also what is causing the error for the OP (before getting to the linker error of no implementation for StringLength). Try to have this declaration instead:
 
int StringLength(const char* x); // Takes a C-String  

@bigorenski shows one way of doing that function, I won't repeat it here.
Last edited on
Sorry, my mistake... it should be like:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
#include <iostream>
#include <cstring>
using std::cout;
using std::cin;
#define MAX_LENGTH 255
int StringLength (char *x){
  
  int len;
  for(len = 0; x[len]!='\0'; ++len);
  return(len);

}


int main(){
  cout<<"\n enter a string: ";
  char c[MAX_LENGTH];
  
  for(int i=0; c[i]!='\n'; ++i){
    if(i==MAX_LENGTH){
        cout<<"\n string too large";
        break;
    }
    c[i] = cin.get();
    
    if(c[i]=='\n'){
        c[i] = '\0';
        break;
    }
 }

 cout<<"The string is: '"<< c<<"' and length is: "<< StringLength(c);

}
Last edited on
Thank you both! I got it:)
Topic archived. No new replies allowed.