我正在尝试为作业编写三个函数
changeUp
将字符串更改为大写changeDown
将字符串更改为小写changeRev
反转每个字符的大小写
每个函数都必须接受指向字符串或 C 字符串的指针作为参数,并且必须通过迭代输入字符串中的每个字符来进行上述更改。
当输入AbCd
时,第一个函数应返回ABCD
;第二个函数应该返回abcd;反向函数应返回 aBcD
。
我不知道如何让最后一个函数工作 - 它只返回所有大写字母。
我尝试将输入复制到变量中以保存它 - 您可以看到我尝试执行此操作的注释区域,但我真的不知道我在做什么,我只是说实话。我在尝试复制(第2行)时遇到了各种错误。
#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;
void changeUp(char *line)//Change to upper case
{
for (int i = 0; line[i]; i++)
{
if (islower(line[i])) line[i] = toupper(line[i]);
}
}
void changeDown(char *line)//Change to lower case
{
for (int i = 0; line[i]; i++)
{
if (isupper(line[i])) line[i] = tolower(line[i]);
}
}
void changeRev(char *line)//Reverse the cases
{
for (int i = 0; line[i]; i++)
{
if (isupper(line[i])) line[i] = tolower(line[i]);
else if (islower(line[i])) line[i] = toupper(line[i]);
}
}
void main()
{
const int SIZE = 81; //For character space
char line[SIZE], line2[SIZE];//Character array
cout << "Enter a string of characters :" <<endl;//Takestring input from user
cin.getline(line, SIZE);
//strcpy_s(line, line2);
changeUp(line);
cout << "Changed to Upper Case " << line << endl;//Output string in all caps
//strcpy_s(line, line2);
changeDown(line);
cout << "Changed to Lower Case " << line << endl;//Output string in lower case
//strcpy_s(line, line2);
changeRev(line);
cout << "The rverse of the characters is " << line << endl;//Output reverse of string entered
system("pause");
return;
}
最佳答案
包含“使用命名空间 std”是不好的做法,最好使用 std::cout 并且适用于该命名空间中的所有函数。此外,您还发送了一个指向函数的指针,因此每次每个函数都修改字符串时,因此在反向条件之前您传递的都是小写字母,因此这就是您获得全部大写字母的原因。我认为像下面这样的解决方案会是更好的方法。
#include <iostream>
#include <string>
using namespace std;
string changeUp(string line)//Change to upper case
{
for (int i = 0; line[i]; i++)
{
if (islower(line[i])) line[i] = toupper(line[i]);
}
return line;
}
string changeDown(string line)//Change to lower case
{
for (int i = 0; line[i]; i++)
{
if (isupper(line[i])) line[i] = tolower(line[i]);
}
return line;
}
string changeRev(string line)//Reverse the cases
{
for (int i = 0; line[i]; i++)
{
if (isupper(line[i])) line[i] = tolower(line[i]);
else if (islower(line[i])) line[i] = toupper(line[i]);
}
return line;
}
void main()
{
const int SIZE = 81; //For character space
char line[SIZE], line2[SIZE];//Character array
cout << "Enter a string of characters :" << endl;//Takestring input from user
cin.getline(line, SIZE);
//strcpy_s(line, line2);
cout << "Changed to Upper Case " << changeUp(line) << endl;//Output string in all caps
//strcpy_s(line, line2);
cout << "Changed to Lower Case " << changeDown(line) << endl;//Output string in lower case
//strcpy_s(line, line2);
cout << "The rverse of the characters is " << changeRev(line) << endl;//Output reverse of string entered
system("pause");
return;
}
关于c++ - 我需要知道如何将 c 字符串从一个变量复制到另一个变量,以便让第三个函数在我的程序中工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35305437/