我有一个问题,我的代码不能够大写第一个字符串后的任何字符串的第一个字母,并且不显示字符串的最后一个字。该代码使用linux重定向从输入文件中读取一系列标题。每个单词的第一个字母需要大写,其余的都是小写,每个单词需要用一个黑色空格分隔。这是测试数据的输出:隐形字符出现在字符串的新行
The 5th the Cat In The one Fish Two Fish Red Fish Blue
还要注意如何存在和第5和鱼和红之间的两个空格
#include <iostream>
#include <iomanip>
#include <cctype>
#include <string>
using namespace std;
void reform (string& imup);
int main()
{
string word;
string temp = " ";
string letters;
getline(cin,letters);
int length;
length = 0;
word = "";
while (cin)
{
length = letters.size();
for (int i =0; i < length; i++)
{
if (letters[i] != ' ' && letters[i] != '\n')
{
word = word + letters[i];
}
else if ((letters[i] == ' ' && isalpha(letters[i-1])) ||
(letters[i] == ' ' && isalpha(letters[i+1])))
{
reform(word);
cout<< word <<" " ;
word = "";
}
else if ((letters[i] == ' ' && isdigit(letters[i-1])) ||
(letters[i] == ' ' && isdigit(letters[i+1])))
{
reform(word);
cout<< word <<" " ;
word = "";
}
}
cout<< endl;
getline(cin,letters);
}
return 0;
}
void reform (string& imup)
{
int size;
// cout <<"hi ";
size = imup.length();
imup[0] = toupper(imup[0]);
for (int i=1; i < size; i++)
imup[i] = tolower(imup[i]);
}
请编辑您的帖子,并正确缩进代码。随机缩进使得其逻辑难以遵循。 –
(不相关)使用'while(getline(..))'而不是两次调用'getline'。 –
您可以将isalpha和isdigit的测试合并到||中。 (这样你就不需要重复合并)。如果一行的第一个字符是空格,这将炸毁。如果空格之前的字符既不是字母也不是数字(如$,@或*),会发生什么情况。 –