@closed account (21CSz8AR)
As you say this is for "C class", but you are using both C syntax and C++ syntax. You wrote
length = StringLength(input);
it should be
length = strlen(input);
, but that will not work because
input
is defined as a C++ string which does not work with a C program.
length = input.length()
does work, but it is not C. There might be a work around for that, but it would not be a C program.
The general concept of the program works and can be made to work, but it becomes more a C++ program.
Hope that helps,
Andy
Correction meant to say, the last printf statement does not work ant there might be a work around... Yes there is a work around, but it is a C++ style syntax.
Played with your program and this is what I came up with:
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
|
string input; // c++ style
//char input[100]; // Does not work with c++ syntax and style
int length{ 0 }, lc{ 1 }; // need to initalize the two ints before use
int Maxlength{ 0 };
string MaxStr;
printf("What do you want your sentence to be? [end] to quit \n");
printf("%d. ", lc++);
getline(cin, input); // c++ syntax
printf("\n");
length = input.length(); // c++ syntax
while (input.compare("end") != 0) // c++ syntax
{
printf("%d. ", lc++);
getline(cin, input);
printf("\n");
length = input.length();
if (length > Maxlength)
{
Maxlength = length;
MaxStr = input;
}
}
// MaxStr.c_str() is c++ syntx to change a string into a c-string.
// With out c_str() the printf will print garbage.
printf("The longest string was \"%s\" with %d characters\n", MaxStr.c_str(), Maxlength);
cout << "\nThe longest string was \"" << MaxStr << "\" with " << Maxlength << " characters" << endl;
|
This is just the code between the braces of main. My header includes are different from what you have. I used:
1 2 3 4 5 6 7
|
#include <iostream>
#include <string>
#include <cstring>
#include <vector>
#include <conio.h>
#include <iomanip>
#include <Windows.h>
|
although not all are needed it is a header file I use for general quick use.