5.12 LAB: Iterating through a C string without using strlen The program in Figure 4.3.1 demonstrates Iterating through a

Business, Finance, Economics, Accounting, Operations Management, Computer Science, Electrical Engineering, Mechanical Engineering, Civil Engineering, Chemical Engineering, Algebra, Precalculus, Statistics and Probabilty, Advanced Math, Physics, Chemistry, Biology, Nursing, Psychology, Certifications, Tests, Prep, and more.
Post Reply
answerhappygod
Site Admin
Posts: 899604
Joined: Mon Aug 02, 2021 8:13 am

5.12 LAB: Iterating through a C string without using strlen The program in Figure 4.3.1 demonstrates Iterating through a

Post by answerhappygod »

5.12 LAB: Iterating through a C string without using
strlen
The program in Figure 4.3.1 demonstrates Iterating through a C
string using strlen. A call for strlen is used in a
for loop:
Since the length of the string does not change within the loop,
we can slightly improve this code fragment by
calling strlen before the loop:
However, this change is not really necessary since most
compilers are designed to transform our code by making it faster
and consume less resources (code
optimization).
Your task is to rewrite this program without
calling strlen.
given code:
#include <iostream>
#include <cstring>
using namespace std;
const int MAX_LENGTH = 16;
int main() {
char userName[MAX_LENGTH]; // = "Alan Turing";
int i;

cout << "Input string: ";
cin.getline(userName, MAX_LENGTH, '\n');
cout << "Before: [" << userName <<
"]" << endl;

//for (i = 0; i < strlen(userName); ++i)
{
for (i = 0; /* Write your code here */ ; ++i) {
if (userName == ' ') {
userName = '_';
}
}
cout << "After: [" << userName
<< "]" << endl;

return 0;
}
Join a community of subject matter experts. Register for FREE to view solutions, replies, and use search function. Request answer by replying!
Post Reply