C++ IBM & EDX Lab: String Length and Pointers

 Yesterday's lab and lesson were on pointers in C++.  Below is an assignment from 1 of the labs. My submitted code is below.  I will be posting the code to Github once the course was been archived.

The assignment was about calculating a string length. However, we had to use a char pointer which made the task difficult.  I started to appreciate Python's string methods.


Lab: String Length

Write a program to calculate the length of the string using a pointer. Get the input string from the user and pass this string to the function. 

Note: Please avoid the usage of exit(0) in your code.  

Implement the following methods.

1. implement ‘stringLength’

Method signature, int stringLength(char* str)

In this method, the input string given by the user is passed as a parameter. Find the length of the input string using a pointer and return it. The char pointer(char *) is passed as an argument to this method.

2. implement ‘main’

Method signature, int main()

In this method, get the input string from the user. Call the method ‘stringLength’ by passing the input string as a parameter.

(Refer to the Sample input and output )

Sample Input 1: 

programming

Sample Output 1:

11

 

Sample Input 2:

Welcome to house

Sample Output 2:

16


My Code (submitted and 100%)


#include <iostream>

#include<string>

#include<cstring>

using namespace std;

 

int stringLength(char* str)

{

    char *t;

    int length = 0;

   

    for (t = str; *t != '\0' ; t++){

        length +=1;

    }

    return length;

}

 

int main(){   //DO NOT change the 'main' signature

    string input;

    int length;

    getline(cin, input);

    char new_str[50]

    strcpy(new_str, input.c_str())

    char *str =new_str;

    length = stringLength(str);

    cout << length << endl;

}




0

Comments

Popular posts from this blog

Space Wars- Python 3

Maze Game in Python using Turtle