-
string help again
I have to ensure that a string entered by the user is all lowercase...
here is the code...
// String.cpp
#include <iostream>
#include <stdlib.h>
#include <ctype.h>
#include "string.h"
using namespace std;
void String::setString()
{
cout << "Enter a description of the appointment ===>";
cin.getline(ch, 100);
}
int String::StringToLower(char *str)
{
while(*str)
{
*str = tolower(*str);
str++;
}
return 0;
}
void String::Print()
{
cout << "Appointment description: ";
StringToLower(str);
cout << str;
cout << endl;
}
int main()
{
String strn;
strn.setString();
strn.Print();
return 0;
}
// Header file String.h
#ifndef _STRING_H_
#define _STRING_H_
class String
{
private:
char ch[100];
char str[100];
public:
void setString();
int StringToLower(char *str);
void Print();
};
#endif
It compiles... but this is the output
Enter a description of the appointment ===>This is a test
Appointment description: ╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠ ╠╠╠╠╠
╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠ └ ↕
Press any key to continue
-
int String::StringToLower(char *str)
{
while(*str)
{
*str = tolower(*str);
str++;
}
return 0;
}
in the above you appear to pass the string to convert by passing it as a pointer because that way when you change the value of things in the string in the function it will change the string whereever it was sent from. However, by changing the value of str doing this: str++; you loose your anchor point back where you started and introduce the error. I would try this:
while(int i < strlen(str))
{
str[i++] = tolower(str[i]);
}