我需要制作一个程序,将字符串中每个句子的第一个字符大写。例如,如果字符串参数是“hello。我的名字是乔。你的名字是什么?“该函数应该操纵字符串,因此它包含”你好。我的名字是乔。你叫什么名字?“我不确定我做错了什么。有什么建议?这是我的代码:
#include<iostream>
#include<cctype>
#include<cstdlib>
using namespace std;
void capitalize(char sentence[], int const SIZE);
int main()
{
const int SIZE = 1024;
char sentence[SIZE];
cout << "Enter a string: " << endl << endl;
cin.getline(sentence, SIZE);
capitalize(sentence, SIZE);
system("pause");
return(0);
}
void capitalize(char sentence[], int SIZE)
{
char *strPtr;
int count = 0;
sentence[0] = toupper(sentence[0]);
for (int i = 0; i < SIZE; i++)
{
strPtr = strstr(sentence[i], ".");
if (*strPtr == '.')
{
*strPtr = toupper(*strPtr);
}
}
while (sentence[count] != '\0')
{
cout << sentence[count];
count++;
}
}
答案 0 :(得分:1)
#include <cstring> // need this for strstr()
void capitalize(char sentence[], int SIZE)
{
char *strPtr;
int count = 0;
sentence[0] = toupper(sentence[0]);
for (int i = 0; i < SIZE; i++)
{
strPtr = strstr(&sentence[i], ".");
//strPtr returns the pointer to
//the first occurence of "." after sentence[i]
if(strPtr==NULL) break;
if (*strPtr == '.')
{
// you really dont want to do this
//*strPtr = toupper(*strPtr);
// put the suitable code here and everything will work
}
}
//why the while loop? and count?
while (sentence[count] != '\0')
{
cout << sentence[count];
count++;
}
}
你在做什么就是大写“。”但显然你希望下一个角色被大写。所以自己编写这部分代码,因为你会发现它更有价值。
答案 1 :(得分:0)
首先,正如评论中所述,您不包括cstring
。其次,您在strstr
上调用sentence[i]
,这是一个字符。你想要sentence + i
这是一个char *。这将修复您的语法错误。
对于逻辑错误,您似乎正在尝试toupper
这段时间。
strPtr = strstr(sentence[i], ".");
应该在i
(包括)的strstr
字符串中找到第一个句点。然后检查strPtr
是否找到了任何内容(如果不是,它将返回null。如果它发现序列为大写strPtr
,但'.'
仍指向第一个字符目标字符串,即". "
。你应该寻找目标字符串strstr
,然后递增一个字符串以找到下一句的第一个字母。不幸的是,没有安全的做法与". "
一起,因为它没有告诉你它看到的字符串有多远,所以字符串只能以'.'
结束,一个过去从数组中掉落。您需要手动迭代数组,查找std::find
然后检查过去,或者改为使用{{1}}。